加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Asp.net Web API规范化参数

发布时间:2020-12-15 04:09:18 所属栏目:百科 来源:网络整理
导读:说我有一个像这样的控制器: public class MyController : ApiController { [Route("{myarg}")] [HttpGet] public async TaskFoo Get(string myarg) { return await ... }} myarg论证需要“规范化”.假设我总是希望修剪它,将其大写并将其反转.实际操作并不重
说我有一个像这样的控制器:
public class MyController : ApiController {
    [Route("{myarg}")]
    [HttpGet]
    public async Task<Foo> Get(string myarg)
    {
        return await ...
    }
}

myarg论证需要“规范化”.假设我总是希望修剪它,将其大写并将其反转.实际操作并不重要,它们只是一个例子,所以我不是在寻找修剪或反转字符串的方法.

我有一堆控制器,包含所有类似参数的所有方法.我希望有一种方法来注释这些方法或做其他事情以确保参数在传递到方法之前始终是“规范化的”.我已经研究了路径约束(特别是custom route constraints),但是没有提供一种方法来做我想要的(这是有意义的,因为它不是一个真正的约束).

理想情况下,我想用以下属性来注释方法:

[MyNormalize("{myarg}")]

或者类似于RouteAttributes的东西.什么是最好的方式来实现这个并以干净的方式实现这一点?

解决方法

值得注意的是,理想情况下,您只需要调整模型绑定,以便正确绑定传递的值,而不是转换它.

无论如何,这是自定义模型绑定器:

public class MyArgModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
    public bool BindModel(HttpActionContext actionContext,System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        // transform to upper-case
        var transformedValue = val.AttemptedValue.ToUpperInvariant();

        bindingContext.Model = transformedValue;

        return true;
    }
}

然后申请:

[Route("{myarg}")]
[HttpGet]
public async Task<Foo> Get([ModelBinder(typeof(MyArgModelBinder))] string myarg)
{
    // at this point,`myarg` would contain the transformed value

    ...
}

见Documentation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读