Wiktor
Wiktor

Reputation: 856

C# Web Api 2 How to redirect request to default controller

I've got a situation where most of the requests will be processed with dedicated controllers.

    config.Routes.MapHttpRoute(
            name: "DataApi",
            routeTemplate: "api/{controller}/{action}",
            defaults: new
            {
                controller = "default"
            }
    );

But there may be a situation where no controller will be found based on URL. Like api/this_controller_is_not_exists/GetStatus.

How can I redirect those requests to default controller called default and process this request using action inside default controller? Valid requests for default controller would look like api/default/GetStatus.

The route will be no much different for valid and invalid request. Valid:

'api/this_controller_exist/GetStatus'

Invalid:

'api/this_controller_not_exists/GetStatus'

Upvotes: 1

Views: 896

Answers (1)

Rahul
Rahul

Reputation: 77866

Well if you have a default route mapping named default and if your controller does really exists then it will automatically map the request to your controller this_controller_exist cause after the requested URI passes through RouteData it will be feeded to HttpControllerSelector which will try to get all the controller in your API project inherits from ApiController using reflection. Thus if the controller in your question does really exists and derives from ApiController then it won't be an issue provided you have a default route mapping in WebApiConfig else if not found it will resort to IIS resource handling which will end up throwing a 404 resource not found error.

Upvotes: 1

Related Questions