如何在路由中定义PUT方法仅限制为不带参数的控制器中的Put方法? [英] How to define the PUT method in routing only limit to the Put methods in controller without parameter?

查看:289
本文介绍了如何在路由中定义PUT方法仅限制为不带参数的控制器中的Put方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是WebApiConfig.cs中的路由配置:

Here is the routing configuration in WebApiConfig.cs:

config.Routes.MapHttpRoute(
    name: "DefaultApiPut",
    routeTemplate: "api/{controller}",
    defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) }
);


config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Post, HttpMethod.Delete) }
);

这是我的控制者:

public class MyController : ApiController {
    [HttpPut]
    public void Put()
    {
        //blah
    }
}

客户端以某种方式发送带有URL / api的PUT请求时/ myController / 12345 ,它仍然映射到 MyController 中的 Put 方法,我是

Somehow when the client sents the PUT request with the URL /api/myController/12345, it still maps to the Put method in MyController, I am expecting an error like resource not found.

如何强制 Put 方法仅接受不带参数的请求?

How to force the Put method only accept the request without a parameter?

预先感谢!

推荐答案

您正在将 httpMethod 约束到默认值中,但它应该在 constraints 中。

You're putting your httpMethod constraint into defaults, but it should be in constraints.

默认值只是说如果请求中不包含某些或全部默认值,默认值将是什么路由参数(对于动词而言,是没有意义的,因为每个HTTP请求始终将动词作为协议的一部分)。 约束限制将激活路线的路线值的组合,而这正是您实际上要执行的操作。

defaults just says what the default values will be if the request doesn't include some or all of them as routing parameters (which in the case of the verb, is meaningless, since every HTTP request always has a verb as part of the protocol). constraints limit the combination of route values that will activate the route, which is what you're actually trying to do.

仅供参考,对于这种简单/标准的路由,您也不需要API控制器中的 [HttpPut] 属性。 HTTP路由已经解决了该问题,该路由将动词映射到controller方法。

FYI, for this simple/standard routing, you don't need the [HttpPut] attribute in an API controller either. That's already handled by the HTTP routing which maps the verb to the controller method.

这篇关于如何在路由中定义PUT方法仅限制为不带参数的控制器中的Put方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆