如何在.Net 7中将Query绑定到数组详解

2023-12-05 0 701
目录
  • 前言
  • 代码演示
  • 借助 IParsable 绑定更复杂的类型
  • 参考资料
  • 总结

前言

在 .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:

总结

到此这篇关于如何在.Net7中将Query绑定到数组的文章就介绍到这了,更多相关.Net7将Query绑定到数组内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 ASP.NET 如何在.Net 7中将Query绑定到数组详解 https://www.u-9.cn/biancheng/aspnet/95468.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务