Generating a route outside of a controller, similar to Url.RouteUrl()
asp.net-mvc, asp.net-mvc-routing
Solution
The following is about the only way:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
However, that comes with caveats:
- There's a hard dependency on `System.Web`
- It must be done within the context of an MVC project (the actual class where this code is can exist outside of the MVC project, but it can only be called from an MVC project).
Problem
I've got a service class in an ASP.NET MVC 5 application that should generate a fully qualified route URL. This class is being called from a controller. In the controller, I'd typically generate the URL to the route like: ``` string myUrl = Url.RouteUrl("ViewCust", new{custId=customerId},Request.Url.Scheme) ``` How can a route URL be generated in a class that's not a controller? I've tried: ``` string myUrl = System.Web.Mvc.UrlHelper() .RouteUrl( routeName, routeValues, HttpContext.Current.Request.Url.Scheme); ``` This results in 'System.ArgumentNullException' Value cannot be null. Parameter name: routeCollection