Quick question regarding routes within MVC and WebAPI. I have added a route to route config.cs:
routes.MapRoute(
name: "ConfirmEmail",
url: "ConfirmEmail/{userid}",
defaults: new { controller = "Email", action = "ConfirmEmail" }
);
This is registered in the global.asax as per normal:
RouteConfig.RegisterRoutes(RouteTable.Routes);
I am trying to generate a URL for use within an email which is sent as part of a function call within a WebAPI controller function. I am using the UrlHelper.Link function to attempt to generate a URL, however I receive an error saying the route cannot be found by name:
var url = Url.Link("ConfirmEmail", new { userid = "someUserId" });
Now I was under the impression route dictionaries were shared in both MVC and WebAPI controller contexts however I cannot see the MVC routes within the route dictionary of the incoming Web API call (on the Request object) however the WebAPI routes I have defined are there.
Am I missing something?
The routing tables for MVC and Web API are completely different. While the syntax looks similar, the route table they operate on is different.
However, MVC uses static objects for configuration, so you can access the global MVC route table from within an API controller using
System.Web.Routing.RouteTable.Routes
.This won't allow you to use Url.Link however, so I would suggest using a constant within your route registration for the format.
Using Richards hint of where to find the routes, I have put together the following function:
It's a bit raw but did the job for me, just thought I'd put this here in case anyone else had the same problem!
Here is a much more cleaner way to generate links to MVC routes from WebApi. I use this method in a custom base api controller.