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?
@Url.Action("Remove", "List", new { httproute = "DefaultApi" })
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).*" }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With