当前位置:网站首页>如何让最小 API 绑定查询字符串中的数组
如何让最小 API 绑定查询字符串中的数组
2022-07-27 05:24:00 【dotNET跨平台】
前言
在上次的文章中,我们实现了《让 ASP.NET Core 支持绑定查询字符串中的数组》:
[HttpGet]
public string Get([FromQuery][ModelBinder(BinderType = typeof(IntArrayModelBinder))] int[] values)
{
return string.Join(" ", values.Select(p => p.ToString()));
}但是,同样的实现方式,在最小 API 上却报错:

那么,使用最小 API 能实现相同功能呢吗?
深入探究
实现扩展方法
通过错误提示,我们发现最小 API 在查找类型的静态 TryParse 方法:
No public static bool int[].TryParse(string, out int[]) method found for values.”于是,我们尝试为int[]类型创建TryParse扩展方法:
public static class IntArrayExtentions
{
public static bool TryParse(this int[] obj, string value, out int[] result)
{
result = value.Trim('[', ']').Split(',').Select(str => int.Parse(str)).ToArray();
return true;
}
}但是,测试发现没有任何效果。
通过调用堆栈:

我们找到了查找静态 TryParse 方法的源代码:
private MethodInfo? GetStaticMethodFromHierarchy(Type type, string name, Type[] parameterTypes, Func<MethodInfo, bool> validateReturnType)
{
bool IsMatch(MethodInfo? method) => method is not null && !method.IsAbstract && validateReturnType(method);
var methodInfo = type.GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, parameterTypes);而type.GetMethod方法是无法获取扩展方法的。
看来此路不通!
自定义类型
既然扩展方法不行,那只能使用定义了静态 TryParse 方法的自定义类型了:
public class DemoDto
{
public int[] Array { get; set; }
public static bool TryParse(string value, out DemoDto result)
{
result = new DemoDto { Array = value.Trim('[', ']').Split(',').Select(str => int.Parse(str)).ToArray() };
return true;
}
}
app.MapGet("/",
(DemoDto values) =>
{
return string.Join(" ", values.Array.Select(p => p.ToString()));
});再次运行,执行成功:

结论
对于路由、查询和标头绑定源,最小 API 通过类型的静态 TryParse 方法来绑定自定义类型。
TryParse 具有两个 API:
public static bool TryParse(string value, out T result);
public static bool TryParse(string value, IFormatProvider provider, out T result);添加微信号【MyIO666】,邀你加入技术交流群
边栏推荐
猜你喜欢

Express接收请求参数

Soul submitted an application for listing in Hong Kong stocks, accelerating the diversified and scene based layout of social gathering places

FTX Foundation funded 15million to help covid-19 clinical trials, which will affect global public health

For redis under windows, it can only read but not write

Lamp -- source code compilation and installation

Is it feasible to fix the vulnerability with one click? Sunflower to tell you that one click fix vulnerability is feasible? Sunflower to tell you that one click fix vulnerability is feasible? Sunflowe

ES6 new features (getting started)

Iptables firewall

ES6新特性(入门)

ESXI虚拟机启动,模块“MonitorLoop”打开电源失败
随机推荐
Shell script delete automatically clean up files that exceed the size
FTX US launched FTX stocks, striding forward to the mainstream financial industry
Shell sentence judgment exercise
Converting ArcGIS style stylesheet files to GeoServer SLD files
Ancient art - make good use of long tail keywords
Ftx.us launched stock and ETF trading services to make trading more transparent
What is special about the rehabilitation orthopedic branch of 3D printing brand?
RAID详解与配置
如何避免漏洞?向日葵远程为你讲解不同场景下的安全使用方法
QGIS series (1) -qgis (server APACHE) win10 installation
Shell -- custom variables and assignments
系统安全与应用
When a subclass calls the constructor of its parent class
Decorator functions and the use of class decorators
shell函数
Project training experience 1
GoLand 编写go程序
LVM and disk quota
Linux安装Redis操作
NAT(网络地址转换)