Search code examples
asp.netresolveurlresolveclienturl

ASP.NET: How to get the virtual path of a file from a generic handler?


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; } }
}

Solution

  • 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.