asp.net - WebApi 字符串操作中的 IModelBinder

标签 asp.net asp.net-web-api

在 Asp.Net MVC 中,System.Web.Mvc.IModelBinder 允许以下实现更改所有字符串:

public class CustomMvcTextBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (result == null)
            return null;

        var value = result.AttemptedValue.Trim().ToUpper();

        return value;
    }
}

然后我将其添加到 ModelBinders 中:

ModelBinders.Binders.Add(typeof(string), new CustomMvcTextBinder());

然而,Asp.Net WebApi 实现 System.Web.Http.ModelBinding.IModelBinder 有一个不同的实现,返回 bool 而不是对象。

如何更改 IModelBinder WebApi 版本中的字符串值?

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

        var value = result.AttemptedValue.Trim().ToUpper();

        return true;
    }
}

最佳答案

您将设置bindingContext.Model并返回true:

var value = result.AttemptedValue.Trim().ToUpper();
bindingContext.Model = value;

return true;

当然,这是假设您的模型只是一个字符串。否则可能需要更多的对象创建/转换。

关于asp.net - WebApi 字符串操作中的 IModelBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33825118/

相关文章:

c# - 启用和禁用控件在 asp.net 中无法正常工作

c# - ASP.Net - RadWindow 的最大化和关闭图标对齐问题

c# - T4 Web API C# 到 Typescript 类库

asp.net-web-api - 分页破坏了 webapi 的其他操作

c# - HttpContent.ReadAsAsync 在哪里?

rest - 如何为 RESTful API 配置 nginx?

c# - system.drawing.image 中的“System.OutOfMemoryException”

c# - 当我们点击 html 按钮时调用函数

c# - asp.net 核心默认代理

c# - 如何将 Stream 转换为对象