4

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.

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
Mike D
  • 4,938
  • 6
  • 43
  • 99

1 Answers1

4

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.

counsellorben
  • 10,924
  • 3
  • 40
  • 38