p.campbell
p.campbell

Reputation: 100667

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

Upvotes: 8

Views: 3860

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239470

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).

Upvotes: 21

Related Questions