I'm writing a helper method for ASP.NET MVC and I need to call Url.Content to get an appropriate URL for the context. However, in order to create a new UrlHelper() I need to get the current RequestContext (System.Web.Routing.RequestContext to be precise) and I'm not sure how to grab it. Anyone know?
views:
1701answers:
6Don't create a new one. Just extend the existing UrlHelper, just like you'd extend HtmlHelper:
public static string IdLink(this UrlHelper helper, Guid id)
{ //...
If you must use both HtmlHelper and UrlHelper, pass one of them as a regular (non-"this") argument.
As mentioned above, just extend the HtmlHelper and the context is exposed in that way. For example:
public static string ExtensionMethodName(this HtmlHelper html,object o)
{
html.ViewContext.HttpContext.Request.Uri ... etc
}
Noticed this was still unanswered. As of MVC 1.0 you can do:
public static string NewHelperMethod(this HtmlHelper helper)
{
UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
No one's actually answered the question: how do you get the Request context to instantiate a UrlHelper?
If I'm trying to use the UrlHelper in a web service method, an extension method doesn't help because I don't have the HtmlHelper either. Is there any way to get the RequestContext for the current httpcontext?
You may have found an answer elsewhere, but here goes;
In a controller action, you can get to the current RequestContext like so:
public ActionResult SomeAction(){
var helper = new UrlHelper(this.ControllerContext.RequestContext);
...
}
If the current IHttpHandler is MvcHandler, you can use
((MvcHandler)HttpContext.Current.Handler).RequestContext