首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IModelBinder中的WebApi字符串操作

IModelBinder中的WebApi字符串操作
EN

Stack Overflow用户
提问于 2015-11-20 11:04:35
回答 1查看 726关注 0票数 2

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

代码语言:javascript
复制
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中:

代码语言:javascript
复制
ModelBinders.Binders.Add(typeof(string), new CustomMvcTextBinder());

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

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

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-20 11:13:00

您将设置bindingContext.Model并返回true

代码语言:javascript
复制
var value = result.AttemptedValue.Trim().ToUpper();
bindingContext.Model = value;

return true;

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33825118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档