1

I'd like to log the requests to my Web API application that results in 404 (which means the routing engine couldn't find a matching service).

How would that be possible?

For example, if I have the below mapping:

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new
                    {
                        id = RouteParameter.Optional
                    }
                );

then calling the below will return 404:

api_rootNotValid/controllername

I want to capture such requests and log them.

I've created a class inheriting from DelegatingHandler but only when the routing engine succeeds finding a service then it goes into the DelegatingHandler.

So I think there should be something else that can help?

tereško
  • 58,060
  • 25
  • 98
  • 150
The Light
  • 26,341
  • 62
  • 176
  • 258
  • 1
    http://haacked.com/archive/2011/04/12/routedebugger-2.aspx and this http://stackoverflow.com/questions/717628/asp-net-mvc-404-error-handling – Ravi Gadag May 21 '13 at 09:39

1 Answers1

0

I think this is a tricky thing to do...some info which you might need to consider:

  • Route matching happens at different stages when compared to WebHost(IIS) and SelfHost. Web API Stack Diagram for reference.

    • WebHost - happens even before any message handlers are run. So your delegating handler wouldn't even be executed if a route doesn't match.
    • SelfHost - happens after the message handlers are run and at the HttpRoutingDispatcher. In this case your Delegating handler would be executed and could probably check for the response's status code, but even this is error prone due to the next point.
  • A 404 response could be due to route not being matched or if the route matched but some application level code has responded with 404 (ex: api/Products/10 can return 404 if product with id 10 was not found). So here the task is to find whether the route matching generated the 404 or the application level code.

Kiran
  • 56,921
  • 15
  • 176
  • 161