Creating URLs from MVC Routes at the Management Level ...

So ... I have a business object / manager that will generate emails.

These letters will contain links to various content on the website ... and therefore should understand MVC routing .. or at least how to create URLs for the website ...

However, my business object will not have access to RequestContext, etc., and email generation is not necessarily the result of a web request to a website (I have a dispatcher that runs on a background thread that will generate emails)

Any ideas on how I can generate my URLs without accessing the request, and therefore cannot use the URLHelper ...

Thoughts?

+3
source share
3 answers

In order to access UrlHelper outside the controller, you need to pass it and the HttpContext routing data. Here is an example:

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;    

HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper =  = new UrlHelper(new RequestContext(context, RouteTable.Routes.GetRouteData(context)));
+3
source

I prefer to define a scheme and make both routing and business logic out of it. Means different implementations of the same URL scheme.

Some reasons:

  • Your routing mechanism may change. For example, in a function, you can switch to the url_rewrite module.
  • Possible problems with load balancing.
  • You do not even have to try to use URLHelper in an undocumented way.

, HttpRequest URLHelper. . HttpContextBase MvcContrib. URL- . , .

+1

In ASP.NET MVC5 (and possibly MVC4 - I'm not sure when it was introduced), you can do this more directly using HttpRequest.RequestContext. For example:

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

Source: https://habr.com/ru/post/1711859/


All Articles