Web Api模型绑定中的文本绑定器

时间:2015-11-20 12:57:07

标签: asp.net-web-api2 model-binding

我有一个简单的文本绑定器来修改我的web api项目中的字符串。此活页夹应更改所有模型中的所有字符串。

public class TextoBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (result == null)
            return false;

        var value = result.AttemptedValue.Trim();

        // value changes here

        bindingContext.Model = value;

        return true;
    }
}

此TextoBinder类已注册为服务:

config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(string), new TextoBinder()));

问题在于,当绑定输入模型时,Web Api不会像MVC在类似的应用程序中那样调用此绑定器。我知道在MVC和Web Api中处理输入数据的方式并不相同,但是我无法使文本绑定器适用于输入。

1 个答案:

答案 0 :(得分:0)

使用模型绑定提供程序,您仍然需要将[TextoBinder]属性添加到参数中,以告知Web API它应该使用模型绑定程序而不是媒体类型格式化程序。

您可以获得this的帮助。

相关问题