Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API route being ignored

I have these two routes defined:

routes.MapRoute(
    name: "GetVoucherTypesForPartner",
    url: "api/Partner/{partnerId}/VoucherType",
    defaults: new { controller = "Partner", action = "GetVoucherTypesForPartner"}
);

routes.MapRoute(
    name: "Default",
    url: "api/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);

In my PartnerProfile controller, I have 2 methods:

public Partner Get(string id)
{ }

public IEnumerable<string> GetVoucherTypesForPartner(string id)
{ }

If I hit the url ~/api/Partner/1234 then, as expected, the Get method is called.
However, if I hit the url ~/api/Partner/1234/VoucherType then the same Get method is called. I am expecting my GetVoucherTypesForPartner to be called instead.

I'm pretty sure something in my route setup is wrong...

like image 380
Alex Avatar asked Mar 12 '26 18:03

Alex


1 Answers

You seem to have mapped standard MVC routes, not Web API routes. There's a big difference. The standard routes are used by controllers deriving from the Controller class, but if you are using the ASP.NET Web API and your controllers are deriving from the ApiController type then you should define HTTP routes.

You should do that in your ~/App_Start/WebApiConfig.cs and not inside your ~/App_Start/RouteConfig.cs.

So go ahead:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "GetVoucherTypesForPartner",
            routeTemplate: "api/Partner/{partnerId}/VoucherType",
            defaults: new { controller = "Partner", action = "GetVoucherTypesForPartner" }
        );

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

and then:

public class PartnerController : ApiController
{
    public Partner Get(string id)
    {
        ...
    }

    public IEnumerable<string> GetVoucherTypesForPartner(string partnerId)
    {
        ...
    }
}

Things to notice:

  • We have defined HTTP routes not standard MVC routes
  • The parameter that the GetVoucherTypesForPartner action takes must be called partnerId instead of id in order to respect your route definition and avoid any confusions
like image 152
Darin Dimitrov Avatar answered Mar 15 '26 08:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!