Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } }
}
like image 230
Ian Boyd Avatar asked Mar 22 '11 03:03

Ian Boyd


1 Answers

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.

like image 91
Mun Avatar answered Nov 15 '22 05:11

Mun