Вопрос

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?

Это было полезно?

Решение

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");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top