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
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
3 Comments
royco
Can I generate a URL another way? I wonder why I need to know the current RequestContext just to generate a new URL.
womp
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.
Tomas Aschan
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.