Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url.Action with WebApi and Controller routes

I have a 2 controllers, 1 of which is WebApi:

public class ListController : ApiController
{        
    public object Remove(string ListId, List<string> ItemIds)
    {
        //removed
    }
}

public class ListController : Controller
{        
    public object Remove(string ListId, List<string> ItemIds)
    {
        //removed
    }
}

My routes are registered in the Global.asax as follows:

WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);

My WebApi route is defined as:

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

When generating a url through @Url.Action("Remove", "List"), the path I get is '/list/remove'. I expected the WebApi route ('/api/list/remove') to be selected, due to the fact the WebApi routes were registered before the other routes.

How can I get @Url.Action to return the WebApi route as expected?

like image 967
Jason Avatar asked Sep 30 '22 06:09

Jason


2 Answers

@Url.Action("Remove", "List", new { httproute = "DefaultApi" })
like image 128
Tom Riley Avatar answered Oct 18 '22 01:10

Tom Riley


For anyone that runs across this not working as expected... If your URL is generated as /List/Remove?httproute=DefaultApi

Verify that your api routes are loaded first! Order is critical.

I also added the constraints to my web route config to help exclude api routes:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
    constraints: new { controller = @"(?!DefaultApi).*" }
);
like image 25
J. Erik Thompson Avatar answered Oct 18 '22 03:10

J. Erik Thompson