C# 在Web API中创建属性模型绑定器
我已经为一个复杂的类创建了ModelBinder。我想在属性上重用此ModelBinder。 因此,在Web API中的属性上使用ModelBinder是可能的。我正在搜索一个提供属性绑定器的示例实现,就像在MVC中一样。 下面是我遇到的参考链接,但这些实现是针对MVC的。 谢谢你的帮助C# 在Web API中创建属性模型绑定器,c#,asp.net-web-api,asp.net-web-api2,custom-model-binder,C#,Asp.net Web Api,Asp.net Web Api2,Custom Model Binder,我已经为一个复杂的类创建了ModelBinder。我想在属性上重用此ModelBinder。 因此,在Web API中的属性上使用ModelBinder是可能的。我正在搜索一个提供属性绑定器的示例实现,就像在MVC中一样。 下面是我遇到的参考链接,但这些实现是针对MVC的。 谢谢你的帮助 我有同样的目标,但是没有找到合适的解决方案来使用binder解析确切的属性,而不是整个模型。然而,有一个解决方案或多或少适合我——它的作用相当类似,但需要用属性标记模型。我知道我有点晚了,但也许会帮助有同样问
我有同样的目标,但是没有找到合适的解决方案来使用binder解析确切的属性,而不是整个模型。然而,有一个解决方案或多或少适合我——它的作用相当类似,但需要用属性标记模型。我知道我有点晚了,但也许会帮助有同样问题的人 解决方案是对所需类型使用自定义的
类型转换器。首先,决定如何解析模型。在我的示例中,我需要以某种方式解析搜索条件,因此我的复杂模型是:
[TypeConverter(typeof(OrderModelUriConverter))] // my custom type converter, which is described below
public class OrderParameter
{
public string OrderBy { get; set; }
public int OrderDirection { get; set; }
}
public class ArticlesSearchModel
{
public OrderParameter Order { get; set; }
// whatever else
}
然后决定如何解析输入。在我的例子中,我只是用逗号分割这些值
public class OrderParameterUriParser
{
public bool TryParse(string input, out OrderParameter result)
{
result = null;
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
var parts = input.Split(',');
result = new OrderParameter();
result.OrderBy = parts[0];
int orderDirection;
if (parts.Length > 1 && int.TryParse(parts[1], out orderDirection))
{
result.OrderDirection = orderDirection;
}
else
{
result.OrderDirection = 0;
}
return true;
}
}
然后创建一个转换器,它将接受查询的一部分,并使用上述规则将其转换为您的模型
public class OrderModelUriConverter : TypeConverter
{
private static readonly Type StringType = typeof (string);
public OrderModelUriConverter()
{
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == StringType)
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var str = value as string;
if (str != null)
{
var parser = new OrderParameterParser()
OrderParameter orderParameter;
if (parser.TryParse(str, out orderParameter))
{
return orderParameter;
}
}
return base.ConvertFrom(context, culture, value);
}
}
转换器的使用在第一个示例中指定。由于您正在解析URI,请不要忘记在控制器的方法中向参数添加[FromUri]
属性
[HttpGet]
public async Task<HttpResponseMessage> Search([FromUri] ArticlesSearchModel searchModel) // the type converter will be applied only to the property of the types marked with our attribute
{
// do search
}
[HttpGet]
公共异步任务搜索([FromUri]ArticlesSearchModel searchModel)//类型转换器将仅应用于使用我们的属性标记的类型的属性
{
//搜索
}
另外,您还可以看一看,其中包含类似的示例以及其他几种解析参数的方法