5

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.

1
  • did you try HttpContext.Current.Request? Commented Mar 11, 2014 at 7:54

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but I'm not in a View, so I can't use the @Url helper neither the Request property.
@JérémieBertrand Can you reach the HttpContext instance?
Good idea. I can't try right now but normally I can use it.
This won't work if you are out of a request (e.g., scheduled job)
@Timotei You will see that many of the classes in ASP.NET MVC will not work outside of the context of a web applicaiton.
2

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

1 Comment

This won't work if you are out of a request (e.g., scheduled job)
0

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

check this for complete description how to do this

1 Comment

A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.