如何将对同一URL的PUT和DELETE请求路由到不同的控制器方法

时间:2012-06-06 18:33:20

标签: asp.net-mvc asp.net-mvc-3 url-routing asp.net-mvc-routing

我正在寻找这个问题的答案,并找到this question,这确实非常相似。然而,那里发布的解决方案似乎并不适合我......我想知道它是否与问题的年龄有关。

给出以下网址:

/my/items/6

我希望此URL的HTTP PUT请求由一个操作方法处理,HTTP DELETE请求由另一个操作方法处理。以下是我定义的路线(请注意这些路线位于某个区域,因此contextAreaRegistrationContext个实例,如果这很重要的话):

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Replace" },
    new
    {
        httpMethod = new HttpMethodConstraint("POST", "PUT"),
    }
);

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Destroy" },
    new
    {
        httpMethod = new HttpMethodConstraint("POST", "DELETE"),
    }
);

URL生成适用于这两种路由,但是在路由传入请求时会出现问题。只有第一个声明的路由正确映射到其各自的操作。

我挖掘了HttpMethodConstraint源代码,发现它并不关心"X-HTTP-Method-Override"参数,只关注HttpContext.Request.HttpMethod

我能够使用以下自定义路由约束类解决此问题:

public class HttpMethodOverrideConstraint : HttpMethodConstraint
{
    public HttpMethodOverrideConstraint(params string[] allowedMethods) 
        : base(allowedMethods) { }

    protected override bool Match(HttpContextBase httpContext, Route route, 
        string parameterName, RouteValueDictionary values, 
        RouteDirection routeDirection)
    {
        var methodOverride = httpContext.Request
            .Unvalidated().Form["X-HTTP-Method-Override"];

        if (methodOverride == null)
            return base.Match(httpContext, route, parameterName, 
                values, routeDirection);

        return 
            AllowedMethods.Any(m => 
                string.Equals(m, httpContext.Request.HttpMethod, 
                    StringComparison.OrdinalIgnoreCase))
            &&
            AllowedMethods.Any(m => 
                string.Equals(m, methodOverride, 
                    StringComparison.OrdinalIgnoreCase))
        ;
    }
}

......以及这些路线定义:

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Replace" },
    new
    {
        httpMethod = new HttpMethodOverrideConstraint("POST", "PUT"),
    }
);

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Destroy" },
    new
    {
        httpMethod = new HttpMethodOverrideConstraint("POST", "DELETE"),
    }
);

我的问题:是否真的有必要通过自定义路由约束来实现这一目标?或者是否有任何方法可以使其与标准MVC&路由类?

1 个答案:

答案 0 :(得分:0)

动作过滤器是你的朋友......

HttpDeleteAttributeHttpPutAttributeHttpPostAttributeHttpGetAttribute