I have a bunch of controllers in my application which are handled by default web api route. And now I am trying to handle case when controller is not existing yet, but I am really interested in its name.
All existing and future controllers will have same route structure
api/{controller}/{id}
Is there a way to capture non existing controllers names without preventing default api routing performed by controller type name.
My current config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Default Api",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Missing Api",
routeTemplate: "api/{name}/{id}",
defaults: new
{
controller = "Missing",
name = RouteParameter.Optional,
id = RouteParameter.Optional
}
);
}
}
When arranged it this order MissingController is never created at runtime. If I reorder routes, actual controllers will not be created.
It is important for me to leave urls same for missing and existing controllers, otherwise this change will require some changes and (especially) unwanted communication with frontend devs.
What to do?
You can try an exception handler as mentioned in the other answer, OR you can capture api
specific 404 Resource not found
error and redirect them to your missing controller.
To do that, add the following custom error module in web.config
<location path="api">
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/api/Missing" />
</httpErrors>
</system.webServer>
</location>
Note: You might need to do a IISRESET.
quick solution, list out your controller routes manually then capture non matches with the missing route.
However, I think the best solution is to catch the missing controller exception with an exception handler
http://www.asp.net/web-api/overview/error-handling/exception-handling
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With