微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在Web API中创建Property Model Binder

我为复杂的类创建了ModelBinder.我想在属性上重用此ModelBinder.
因此可以在Web API中的属性上使用ModelBinder.我正在寻找一个示例实现,它提供了像MVC中的属性绑定器.
下面是我遇到的参考链接,但这些实现是针对MVC的.
任何帮助赞赏.

Reference Link 1

Reference Link 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,其中包含类似示例以及其他几种解析参数的方法.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐