Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a route outside of a controller, similar to Url.RouteUrl()

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

like image 368
p.campbell Avatar asked Feb 16 '15 20:02

p.campbell


1 Answers

The following is about the only way:

var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

However, that comes with caveats:

  1. There's a hard dependency on System.Web
  2. 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).
like image 144
Chris Pratt Avatar answered Sep 21 '22 12:09

Chris Pratt