开发者

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

开发者 https://www.devze.com 2023-02-19 07:55 出处:网络
How can i resolve a virtual path to a file into a path, suitable for the browser, from within a generic .ashx 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开发者_Go百科

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号