Creating a route outside the controller, similar to Url.RouteUrl ()

I have a class of service in an ASP.NET MVC 5 application that should generate the full route URL.

This class is called from the controller.

In the controller, I usually generate a route URL, for example:

 string myUrl = Url.RouteUrl("ViewCust", new{custId=customerId},Request.Url.Scheme)

How can I create a route URL in a class that is not a controller?

I tried:

string myUrl = System.Web.Mvc.UrlHelper()
            .RouteUrl(
            routeName,
            routeValues,
            HttpContext.Current.Request.Url.Scheme);

The result is

'System.ArgumentNullException' The value cannot be null. Parameter Name: routeCollection

+4
source share
1 answer

The following is the only way:

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

However, this is due to reservations:

  • There is a heavy dependence on System.Web
  • MVC ( , MVC, MVC).
+11

All Articles