Question

I've got a .NET WebApi solution. I'm constraining access to HTTPS but conditionally allowing HTTP traffic. One of the conditions is that all HTTP requests must use the HTTP POST method, passing the x-http-method-override header to supply the intended method so the request can be properly routed. I've configured a global DelegatingHandler to validate all incoming requests and perform the redirection if needed.

With standard routing everything works great. When I configure AttributeRouting things go off the rails. It appears that AttributeRouting attempts to locate the route before the DelegatingHandler modifies the request, resulting in improper routes or IIS 404 errors. Is there a way to intercept the route before the AttributeRouting handler resolves the route?

More info: The project is hosted on IIS (not self hosted). The AttributeRouting I'm using is what comes in WebApi 2.0. The DelegatingHandler is defined thusly in App_Start:

GlobalConfiguration.Configuration.MessageHandlers
    .Add(new MyCustomDelegateHandler());

AttributeRouting is configured simply using:

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

The routes are defined using the attributes:

[HttpGet("api/test/v1/users")]
Was it helpful?

Solution

Couple of question for clarity...Is this a Selfhost or Webhost(IIS) scenario? By AttributeRouting you mean the built-in Web API 2 attribute routing and not TimMcCall's attribute routing nuget package...right?

There have always been differences between when route matching occurs between Selfhost and Webhost. In Selfhost, route matching happens after message handlers are run, where as in case of Webhost route matching happens before message handlers are run.

If your scenario is Webhost, then I would expect the behavior to not change...but if your are seeing different behavior, then can you share how your route configuration (WebApiConfig.cs & the attributed controller/action) look like?

In Webhost, to intercept requests before route matching happens, you could create a Owin middleware which sits before the request is received by Web API. In this middleware you can modify the request details as you need.

NOTE:
Based on the update "More Info" in the post above, pre-RTM bits were being used where this seems to be an issue and this is not longer a problem with the final RTM bits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top