Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an url in ASP.NET MVC outside a view or controller

Tags:

c#

asp.net-mvc

I follow the article "Simulate a Windows Service using ASP.NET to run scheduled jobs" on CodeProject, and in the part "Store item in cache again upon expire" I need to hit a page of my application.

Instead of hard writing the url, I wanted to generate it with the Asp.Net MVC UrlHelper but it seams that it required some instances that I don't have access in this context, because it's not in a Controller or a View.

Is it possible or is there another solution?

EDIT:

Sadly HttpContext.Current is not accessible in CacheItemRemovedCallBack. So the only solution appears to store the value needed (Url.Host) in the Application_Start method in order to build the full url later.

like image 270
Jérémie Bertrand Avatar asked Mar 11 '14 06:03

Jérémie Bertrand


2 Answers

You can use Url.Action method with the following parameters:

@Url.Action("Index", "Home", routeValues, Request.Url.Scheme)

or

new UrlHelper(HttpContext.Request.RequestContext).Action("Index", "Home", routeValues, Request.Url.Scheme)
like image 177
Ufuk Hacıoğulları Avatar answered Oct 15 '22 23:10

Ufuk Hacıoğulları


You can create your own instance of UrlHelper. For this, you need to have an access to current http request. This could be achieved using static instance of HttpContext : HttpContext.Current:

new UrlHelper(HttpContext.Current.Request.RequestContext).Action("action");
like image 2
Kek Avatar answered Oct 15 '22 21:10

Kek