国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

如何在.Net 7中將Query綁定到數(shù)組詳解

瀏覽:180日期: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
主站蜘蛛池模板: 门头沟区| 台山市| 彰武县| 张家口市| 准格尔旗| 红原县| 桑植县| 台前县| 九龙坡区| 依安县| 雷波县| 桓台县| 平泉县| 日照市| 齐齐哈尔市| 南城县| 丹巴县| 都匀市| 甘德县| 宜昌市| 武山县| 香格里拉县| 搜索| 福州市| 灵璧县| 辉县市| 定结县| 东乡县| 永兴县| 阿鲁科尔沁旗| 潮州市| 隆化县| 周至县| 抚顺市| 桑日县| 集安市| 开原市| 博兴县| 崇仁县| 巩义市| 阜阳市|