ResolveUrl without an ASP.NET Page
Asked Answered
B

3

70

I am looking for a way to resolve a relative url the way you would with a page or control instance (MSDN Docs) such as:

Page.ResolveUrl("~/common/Error.aspx");

...but when I only have an HttpContext available to me, such as when I am in a HttpHandler.

Will I need to use a custom function, such as the one seen here?

Or is there a way to get at the underlying function used by the Page.

Benge answered 4/2, 2011 at 0:31 Comment(0)
H
119

Try to get the page from the handler and use ResolveUrl, or create a Control object...

(HttpContext.Current.Handler as Page).ResolveUrl("~/virtualpath");

Or use VirtualPathUtility.ToAppRelative(string) or VirtualPathUtility.ToAbsolute(string)

For example:

System.Web.VirtualPathUtility.ToAbsolute("~/Styles/Contoso.xslt");

returns

/WebSite/Styles/Contoso.xslt
Homeric answered 4/2, 2011 at 2:7 Comment(1)
in an IHTTPHandler and IHttpModule HttpContext.Current.Handler is null!Bael
U
17

This question on SO (ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function) looks kind of helpful...Basically, you can use the VirtualPathUtility class which is under the System.Web namespace. There is an additional answer to that question which says to be careful of QueryString parameters, but a solution to that is also provided.

At the same time, Rick Strahl's code is pretty neat!

Unsecured answered 4/2, 2011 at 0:49 Comment(1)
which good patterns and practices ? System.Web.VirtualPathUtility, HttpContext.Current.Handler or Rick Strahl's code ?Egin
J
1

Use something like this - Controls is a folder name in your application and myController is the controller name. to create and instance and load the controller you can do it by:

Controls_myController ctrl = Page.LoadControl(Page.ResolveUrl("controls/myController.ascx"));

Hope this helps.

Jorrie answered 27/8, 2013 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.