views:

1701

answers:

6

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?

+1  A: 

Don'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.

Craig Stuntz
+1  A: 

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    
    }
ccook
+2  A: 

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);
Martijn Laarman
I wanted to know how to do this from the controller, this answer gave me enough information to figure out that I wanted ControllerContext.RequestContext.
lambacck
+1  A: 

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?

marcel_g
Agreed - this worked for me: http://jwwishart.wordpress.com/2009/12/04/getting-a-requestcontext-outside-of-the-controllers-and-views-in-mvc/
sydneyos
+1  A: 

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);
  ...
}
jobolito
+7  A: 

If the current IHttpHandler is MvcHandler, you can use

((MvcHandler)HttpContext.Current.Handler).RequestContext
felixg
This is actually what I needed...from a truely static context
Kevin
Saved my day, thank you so much!
Barbaros Alp