MVC5 - Url.RouteUrl not returning Attribute Routing URL of Web API action

Topics: ASP.NET MVC, ASP.NET Web API
Nov 10, 2013 at 1:10 PM
Hello,

I created a MVC 5 site using its template and added the following API controller:
namespace MvcSite.Controllers {

      public class TestController : ApiController {

        [Route("test/send"), HttpGet]
        public String Send() {
          return "SENT";
        }

      } // TestController
    } // MvcSite.Controllers
When I access "/test/send" I get the string "SENT" back as expected ...

In a Razor view or in a Controller I need to get the URL of the send action so I tried:
var url = Url.RouteUrl(new { controller = "Test", action = "Send", HttpRoute = true });
But url is null ... I have no idea why ...

The API route is working fine so it is in the Route Table ...

What am I missing?

Thank You,
Miguel
Developer
Nov 10, 2013 at 3:41 PM

To generate links based on a Web API route, you need to always supply a route name. Also note that you could use “Url.HttpRouteUrl” extension to generate links to Web API. (in this case you need not use ‘httproute=true’)