在 .Net 7 中,我們可以通過綁定數組的方式來接收來自查詢字符串的參數。這樣就不需要再使用逗號分隔的字符串來獲取參數了。
代碼演示
假設我們需要從 query 上接受多個 id 并返回查詢的結果。例如:id=1&id=2
在 .Net 7 中,我們可以這樣實現:
public?ActionResult?GetResults([FromQuery]int[]?ids)
{//?使用?ids?數組查詢結果
}
這樣就可以直接將 id=1&id=2 這樣的查詢字符串綁定到 ids 數組上。
借助 IParsable 綁定更復雜的類型
如果我們需要綁定的類型比較復雜,例如:
public?ActionResult?GetResults([FromQuery]MyDate[]?dates)
{//?使用?dates?數組查詢結果
}
我們可以通過實現 IParsable<T>
接口來實現自定義的綁定。
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[]
數組上了。
參考資料
Bind arrays and string values from headers and query strings[1]
本文采用 Chat OpenAI 輔助注水澆筑而成,如有雷同,完全有可能。
本文作者:newbe36524
本文鏈接:https://www.newbe.pro/ChatAI/How-to-binding-query-to-array-in-dotnet-7/
版權聲明:本博客所有文章除特別聲明外,均采用 BY-NC-SA 許可協議。轉載請注明出處!
參考資料
[1]
Bind arrays and string values from headers and query strings: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis?preserve-view=true&view=aspnetcore-7.0&WT.mc_id=DX-MVP-5003606#bind-arrays-and-string-values-from-headers-and-query-strings