Search code examples
c#asp.netasp.net-web-api2asp.net-mvc-routingasp.net-web-api-routing

Routes with different handler in web api asp.net


Hi people I need help about a problem with routes and handler in web api. I have two routes, I want that one route uses a custom handler, the other routes uses default. I have this code.

config.Routes.MapHttpRoute(

            name: "NamedActions",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional },
            handler: customConfig.MessageHandlers.Add(new BasicHandler(new Repository()))
        );

config.Routes.MapHttpRoute(
            name: "ApiLogin",
            routeTemplate: "apiLogin/v1/LoginApi",
            defaults: new { controller = "LoginApi"}//,
        );

but when I put handler: customConfig.MessageHandlers.Add(new BasicHandler(new Repository())) that throw me an error (Error 43 The best overload for 'MapHttpRoute' does not have a parameter named 'handler').

I want the first route uses the handler BasicHandler() with the Repository(), the other one without this custom handler. Is this possible, have two routes with different handler?.


Solution

  • I found the solution for my problem, I miss an attributte in config.Routes.MapHttpRoute , if I want to put the attribute handler, I must to put the attribute constraint first and later the handler attribute. for example:

    config.Routes.MapHttpRoute(

            name: "NamedActions",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraint: null,
            handler: customConfig.MessageHandlers.Add(new BasicHandler(new Repository()))
        );