Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a URL independant of controllers in ASP.NET MVC 3

I have an mvc 3 application with a background thread checking on the state of some database items. When it finds an expired item, it sends out an email. In the email, I would like to include the url for the action to call to see the status. If this was done from a controller I would use the UrlHelper, eg:

string body_url = "For more details see: " + Url.Action("Details", "MyOrder", new { OrderId = order.OrderId }, Constants.HttpProtocol);

However, I'm not in a controller, nor is my method called from a controller, it is started on application start. Is there a way to generate a valid UrlHelper, or, if not, to generate a valid URL without resorting to hard-coding paths, when independent of the controllers?

like image 377
Simon Parker Avatar asked Oct 05 '22 01:10

Simon Parker


1 Answers

This is theoretical... ref msdn and so ... being on a background thread makes things interesting :)

var request = new HttpRequest("/", "http://example.com", ""); //hopefully you can hardcode this or pull from config?
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);

var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);

var urlHelper = new UrlHelper(requestContext);
var url = urlHelper.Action("ActionName", "ControllerName");
like image 181
felickz Avatar answered Oct 10 '22 02:10

felickz