我为一个复杂的类创建了 ModelBinder。我想在一个属性上重用这个 ModelBinder。那么是否可以在 Web API 中的属性上使用 ModelBinder。我正在寻找一个示例实现,它提供类似于 MVC 中的属性绑定器。下面是我遇到的参考链接,但这些实现是针对 MVC 的。任何帮助表示赞赏。
问问题
1624 次
1 回答
2
我有相同的目标,但是没有找到合适的解决方案来使用活页夹解析确切的属性,而不是整个模型。但是,有一个解决方案或多或少适合我——它的行为方式非常相似,但需要用属性标记模型。我知道我有点晚了,但也许会帮助有同样问题的人。
解决方案是对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
}
此外,您可以查看这篇优秀的文章,其中包含类似的示例以及其他几种解析参数的方法。
于 2017-02-15T13:17:56.697 回答