I need a custom IHttpControllerSelector
which should be applied to a specific route only. All other web api routes should use the default implementation of IHttpControllerSelector
.
While researching I found the following code that is meant to replace the IHttpControllerSelector at application start, but it replaces the default controller selector completely, which causes that all routes in the application use my custom controller selector:
config.Services.Replace(typeof(IHttpControllerSelector),
new CustomControllerSelector(config));
Is there a way to configure the IHttpControllerSelector
for a single route?
You can assign a per-route message handler to the route that needs to use a different controller selection logic. This handler would mark the
HttpRequestMessage
with a flag that this request needs to be treated differently.Then simply make the
CustomControllerSelector
inherit fromDefaultHttpControllerSelector
and inspect that flag:DefaultHttpControllerSelector
)Here is the code:
1) message handler, setting the flag
2) assigning per route message handler to the specific route only (do not run for other routes)
3) custom selector respecting the flag:
4) registering the selector:
edit
If you wish to not inherit from
DefaultHttpControllerSelector
- then implementIHttpControllerSelector
directly, and instead of calling thebase.SelectController(request)
save the old selector as a field/property in your classThen just change the registration: