1

I have the following helper method:

    public static String ResolveUrl(String url)
    {
        url = url.Trim();
        if (!(url[0] == '~')) return url;
        try
        {
            if (VirtualPathUtility.IsAppRelative(url)) return VirtualPathUtility.ToAbsolute(url);
            return url;
        }
        catch (HttpException)
        {
            return url;
        }
    }

The problem is that it raises an exception if the provided URL contains a querystring, eg. ~/showcase/View.aspx?id=10783.

Stack trace:

System.Web.HttpException was caught
  Message='~/showcase/View.aspx?id=10783' is not a valid virtual path.
  Source=System.Web
    ErrorCode=-2147467259
    StackTrace:
         at System.Web.VirtualPath.Create(String virtualPath, VirtualPathOptions options)
         at System.Web.VirtualPathUtility.IsAppRelative(String virtualPath)
         at Ctf.Common.ResolveUrl(String url) in [redacted]Common.cs:line 359
    InnerException: 

What's the problem here? Does VirtualPathUtility just not support querystring URLs?

Edit: I should add that the helper is perfectly fine with other app-relative URLs as long as there isn't a querystring on them.

Edit2: I've made a hack workaround by removing the querystring from the URL before calling the VirtualPathUtility methods, then gluing it back on at the end. I'd rather avoid this if possible.

mm201
  • 526
  • 4
  • 15
  • 2
    does it perhaps expect an absolute url, and is rejecting yours since it doesn't have `http://example.com/~....`? – Marc B Aug 20 '14 at 20:20
  • The whole point of `VirtualPathUtility.IsAppRelative` is to detect whether the URL is an app-relative path, ie. begins with `~/`. – mm201 Aug 20 '14 at 20:24

1 Answers1

1

If you are using .NET 3.5 and below, then you are right, VirtualPathUtility will not accept a query string as a valid part of a virtual path for those methods. You'll have to trim off the query string and re-append it on your absolute URL. Check out this excellent question / answer Why do I get an HttpException from VirtualPathUtility ToAbsolute with some paths?.

Community
  • 1
  • 1
p e p
  • 6,593
  • 2
  • 23
  • 32