5

How can i resolve a virtual path to a file into a path, suitable for the browser, from within a generic .ashx handler?

e.g. i want to convert:

~/asp/ClockState.aspx

into

/NextAllowed/asp/ClockState.aspx

If i were a WebForm Page, i could call ResolveUrl:

Page.ResolveUrl("~/asp/ClockState.aspx")

which resolves to:

/NextAllowed/asp/ClockState.aspx

But i'm not a WebForm Page, i'm a generic handler. You know, that IHttpHandler object with all kinds of things injected:

public class ResetClock : IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
        //[process stuff]

        //Redirect client
        context.Response.Redirect("~/asp/ClockState.aspx", true);
    }

    public bool IsReusable { get { return false; } }
}
Nuno Agapito
  • 220
  • 3
  • 12
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219

1 Answers1

7

You can use the VirtualPathUtility class to do this. This contains various methods for working with paths. The one you need is ToAbsolute(), which will convert a relative path to an absolute one.

var path = VirtualPathUtility.ToAbsolute("~/asp/ClockState.aspx");

However, you can use the tilde in Response.Redirect calls anyway, so the following would still work:

Response.Redirect("~/asp/ClockState.aspx");

You do not need to convert the URL to an absolute path before using Response.Redirect.

Mun
  • 14,098
  • 11
  • 59
  • 83
  • i thought i had tried simply `Response.Redirect(...)` and it didnt' take into account the virtual folder. But both `VirtualPathUtility` and just `Redirect` work. +1 accepted. – Ian Boyd Mar 22 '11 at 04:07