5

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?

Simon Parker
  • 1,656
  • 15
  • 37

1 Answers1

4

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");
Community
  • 1
  • 1
felickz
  • 4,292
  • 3
  • 33
  • 37
  • It seems a shame to have to hard-code the base URL, especially given it can change depending on whether I am running test or production. I would have hoped there was some way of grabbing the base URL from the app. – Simon Parker Feb 13 '13 at 21:35
  • You can pass the HttpContext.Current information into your background thread when you spin it up.. be sure to only use the base url portion of it though! http://stackoverflow.com/questions/3398717/asp-net-get-websites-url-without-httpcontext-current-running-in-background-t – felickz Feb 13 '13 at 22:07
  • `HttpContext.Current` isn't available at application start, which is when @SimonParker wants to be able to generate a route URL. – Paul d'Aoust Jul 28 '15 at 23:46
  • 1
    @SimonParker You can do some tricky stuff with `Microsoft.Web.Administration.WebConfigurationManager` to get a list of current site bindings at runtime. Then you can just grab the first binding. It's ugly, but it works! – Paul d'Aoust Jul 28 '15 at 23:47