【发布时间】:2019-10-30 11:54:26
【问题描述】:
我有代表不同类型 ID 的结构。该结构具有 int 属性“Id”、带有 (int id) 参数的公共构造函数并实现 IEquatable 接口。我希望我的 ASP.Net Core WebAPI 应用程序以某种方式将这些结构绑定到查询中的传入整数 Id。我知道有自定义模型绑定器,但是要使用它,我需要为所有查询模型实现自定义模型绑定器,因为用自定义模型绑定器标记每个键结构属性还不够 - 我需要注册自定义模型绑定器提供程序,我切换 ModelType 并返回单个模型绑定器,如下所示:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(DogQueryModel))
{
return new BinderTypeModelBinder(typeof(DogQueryModelBinder));
}
所以我不能只为每个 Id 结构创建一个模型绑定器 - 需要为每个查询模型创建它。
为了清楚起见,我将提供该结构、查询模型和操作的一些示例代码:
public struct DogKey : IEquatable<DogKey>
{
public DogKey(int id)
{
Id = id;
}
public int Id { get; }
#region IEquatable implementation
#endregion IEquatable implementation
}
public class DogQueryModel
{
public DogKey Id { get; set; }
public SomeOtherKey OtherId { get; set; }
public string Name { get; set; }
}
[HttpGet("dog")]
public async Task<ActionResult<IList<DogResultModel>>> GetDogs([FromQuery]DogQueryModel dogQueryModel)
{
//use dogQueryModel.Id as DogKey struct
}
我想这样查询:https://localhost/api/v1/dogs/dog?id=1&otherId=2&Name=dogname
【问题讨论】:
标签: c# asp.net-core design-patterns