ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function
Asked Answered
B

3

35

What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:

Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")

Or C#:

System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");

But I realize that isn't the best way of calling it.

Blynn answered 25/8, 2008 at 20:31 Comment(0)
C
48

I use System.Web.VirtualPathUtility.ToAbsolute.

Crouch answered 25/8, 2008 at 20:35 Comment(0)
D
23

It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is not a perfect replacement for Control.ResolveUrl.

There is at least one significant difference: Control.ResolveUrl handles Query Strings very nicely, but they cause VirtualPathUtility to throw an HttpException. This can be absolutely mystifying the first time it happens, especially if you're used to the way that Control.ResolveUrl works.

If you know the exact structure of the Query String you want to use, this is easy enough to work around, viz:

public static string GetUrl(int id)
{
    string path = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");
    return string.Format("{0}?id={1}", path, id);
}

...but if the Query String is getting passed in from an unknown source then you're going to need to parse it out somehow. (Before you get too deep into that, note that System.Uri might be able to do it for you).

Driggers answered 9/2, 2009 at 13:48 Comment(1)
This may not be true any more. In .NET 4 when I evaluate VirtualPathUtility.ToAbsolute("~/bar/baz?qux=123&quux=456", "/foo") I get /foo/bar/baz?qux=123&quux=456Burrstone
J
3

I tend to use HttpContext.Current to get the page, then run any page/web control methods off that.

Jules answered 25/8, 2008 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.