Search code examples
c#asp.netasp.net-mvcasp.net-web-apiasp.net-mvc-routing

MVC routing troubles


Really having trouble getting to grips with MVC routing despite reading loads of blogs and tutorials on it...

I have this webapi function:

public HttpResponseMessage UpsertProducts([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergProduct> heisenbergProducts)

and the default route in Route.config:

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

All worked fine.

I've now added another function:

public HttpResponseMessage ReviseInventory([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergReviseInventory> heisenbergReviseInventories)

Despite the action names being different, there seems to be a conflict and when calling either of them I get a 500 internal server error - I guess it doesn't know which one to use.

I'm calling them using URL:

api/webapiproducts/upsertproducts?marketplaceId={0}&datasourceId={1}

I tried to get around the issue by using attribute routing:

[Route("/api/WebApiProducts/upsertproducts/{marketplaceid}/{datasourceid}")]
public HttpResponseMessage UpsertProducts([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergProduct> heisenbergProducts)

and

[Route("/api/WebApiProducts/reviseinventory/{marketplaceid}/{datasourceid}")]
public HttpResponseMessage ReviseInventory([FromUri] int marketplaceId, [FromUri] int datasourceId, [FromBody]List<HeisenbergReviseInventory> heisenbergReviseInventories)

Neither of my routing attributes seem to work. What am I doing wrong and what am I not understanding about routing here?

As @Nkosi pointed out I'd put the wrong route file! Here is my WebApiConfig.cs contents:

config.MapHttpAttributeRoutes();

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

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

Solution

  • Managed to get it working with attribute routing by changing the URL I'm calling to this:

    string.Format("api/webapiproducts/reviseinventory/{0}/{1}", marketplaceId, datasourceId);