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

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.

Upvotes: 5

Views: 5890

Answers (3)

yarg
yarg

Reputation: 709

[https://www.codemag.com/Article/1312081/Rendering-ASP.NET-MVC-Razor-Views-to-String][1]

check this for complete description how to do this

Upvotes: 0

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

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)

Upvotes: 5

Kek
Kek

Reputation: 3195

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");

Upvotes: 2

Related Questions