【问题标题】:Text Binder in Web Api Model BindingWeb Api 模型绑定中的文本绑定器
【发布时间】:2015-11-21 04:09:53
【问题描述】:

我有一个简单的文本绑定器来修改我的 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 中处理传入数据的方式不同,但我无法使文本绑定器适用于输入。

【问题讨论】:

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


    【解决方案1】:

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

    您可以向this寻求帮助。

    【讨论】:

    • 谢谢@Guanxi,因为这个话题看起来很重要,我会阅读更多相关内容。
    • 我添加了文档链接,这对我理解这一点很有帮助。
    猜你喜欢
    • 2012-08-28
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多