文章詳情頁
如何在.Net 7中將Query綁定到數(shù)組詳解
瀏覽:305日期:2022-06-09 08:55:45
目錄
- 前言
- 代碼演示
- 借助 IParsable 綁定更復(fù)雜的類型
- 參考資料
- 總結(jié)
前言
在 .Net 7 中,我們可以通過綁定數(shù)組的方式來接收來自查詢字符串的參數(shù)。這樣就不需要再使用逗號(hào)分隔的字符串來獲取參數(shù)了。
代碼演示
假設(shè)我們需要從 query 上接受多個(gè) id 并返回查詢的結(jié)果。例如: id=1&id=2
在 .Net 7 中,我們可以這樣實(shí)現(xiàn):
public ActionResult GetResults([FromQuery]int[] ids)
{
// 使用 ids 數(shù)組查詢結(jié)果
}
這樣就可以直接將 id=1&id=2 這樣的查詢字符串綁定到 ids 數(shù)組上。
借助 IParsable 綁定更復(fù)雜的類型
如果我們需要綁定的類型比較復(fù)雜,例如:
public ActionResult GetResults([FromQuery]MyDate[] dates)
{
// 使用 dates 數(shù)組查詢結(jié)果
}
我們可以通過實(shí)現(xiàn) IParsable<T> 接口來實(shí)現(xiàn)自定義的綁定。
public class MyDate : IParsable<MyDate>
{
public int Month { get; set; }
public int Day { get; set; }
public void Parse(string input)
{
var parts = input.Split("-");
Month = int.Parse(parts[0]);
Day = int.Parse(parts[1]);
}
public static MyDate Parse(string s, IFormatProvider? provider)
{
var date = new MyDate();
date.Parse(s);
return date;
}
public static bool TryParse(string? s, IFormatProvider? provider, out MyDate result)
{
try
{
result = Parse(s, provider);
return true;
}
catch
{
result = default;
return false;
}
}
}
這樣就可以通過 dates=1-1&dates=2-2 這樣的查詢字符串來綁定到 MyDate[] 數(shù)組上了。
參考資料
總結(jié)
到此這篇關(guān)于如何在.Net 7中將Query綁定到數(shù)組的文章就介紹到這了,更多相關(guān).Net7將Query綁定到數(shù)組內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
標(biāo)簽:
ASP.NET
排行榜

網(wǎng)公網(wǎng)安備