1

I'm creating a Shared (static) method in ASP.NET MVC so it can be used by any controller in my project. This static method needs to generate a URL. I think I need to use System.Web.Mvc.UrlHelper, but I can't figure out how to call it from within a static method. The constructor seems to want a RequestContext. Any ideas?

1 Answer 1

1

AFAIK, there is no way to get the "current" RequestContext statically. You'll need to pass in the RequestContext from the controller that's calling it. Any controller can do that by just using this code:

this.ControllerContext.RequestContext
Sign up to request clarification or add additional context in comments.

3 Comments

Can I generate a URL another way? I wonder why I need to know the current RequestContext just to generate a new URL.
UrlHelper is a pretty good way of doing it. You can also generate relative URLs using the routing mechanisms directly, but you'd need to pass in routing information instead.
Bob: The RequestContext is necessary because the generated URL will be relative to whatever URL the browser requested. (As you use routing, the browser has no idea that the file served isn't actually where it is "pretended" to be...) Without the RequestContext there's no way for the UrlHelper to know what the current URL is, and thus no way to generate a relative URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.