我为复杂的类创建了ModelBinder。我想在属性上重用此ModelBinder。 因此可以在Web API中的属性上使用ModelBinder。我正在寻找一个像MVC一样提供属性绑定的示例实现。 下面是我遇到的参考链接,但这些实现是针对MVC的。 任何帮助赞赏。
答案 0 :(得分:2)
我有相同的目标,但是没有找到合适的解决方案来使用binder来解析确切的属性,而不是整个模型。但是,有一种解决方案或多或少地适合我 - 它以相同的方式起作用,但需要用属性标记模型。我知道我有点晚了,但也许会帮助有同样问题的人。
解决方案是使用自定义TypeConverter
作为所需类型。首先,决定如何解析模型。在我的例子中,我需要以某种方式解析搜索条件,所以我的复杂模型是:
[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
}
此外,您可以查看this excellent article,其中包含类似示例以及其他几种解析参数的方法。