JC Grubbs
JC Grubbs

Reputation: 40311

How do you get access to the current System.Web.Routing.RequestContext from within a custom helper method in ASP.NET MVC?

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?

Upvotes: 22

Views: 12369

Answers (5)

felixg
felixg

Reputation: 972

If the current IHttpHandler is MvcHandler, you can use

((MvcHandler)HttpContext.Current.Handler).RequestContext

Upvotes: 46

user91047
user91047

Reputation:

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);
  ...
}

Upvotes: 3

Martijn Laarman
Martijn Laarman

Reputation: 13536

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);

Upvotes: 19

ccook
ccook

Reputation: 5959

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    
    }

Upvotes: 2

Craig Stuntz
Craig Stuntz

Reputation: 126547

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.

Upvotes: 1

Related Questions