Responding to HEAD Request in asp.NET MVC 3

后端 未结 1 1240
难免孤独
难免孤独 2020-12-21 05:55

Is there a way in Asp.NET MVC 3 to respond to HEAD requests in a generic way, as opposed to adding the HEAD attribute to individual methods.

相关标签:
1条回答
  • 2020-12-21 06:29

    Create a route with a RouteConstraint like so:

    routes.MapRoute(
        "HEAD Requests",
        "{*fullPath}",
        new { controller = "Head", action = "Index" },
        new { fullPath = new MustBeHeadRequest() }
    );
    
    public class MustBeHeadRequest : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return httpContext.Request.HttpMethod.ToLowerInvariant() == "head";
        }
    }
    

    Place the route at or near the top of your routes. When a HEAD request comes in, it will be routed to HeadController's Index action.

    0 讨论(0)
提交回复
热议问题