从不继承System.Web.Ui.Page的对象获取文件的URL [英] Get URL of file from object that does not inherit System.Web.Ui.Page

查看:60
本文介绍了从不继承System.Web.Ui.Page的对象获取文件的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,该对象需要位于我的Web应用程序根目录中的文件的URL.如果这是从System.Web.Ui.Page继承的对象,则只使用httpRequest对象.但是,由于该对象不是我不确定如何获取此url.根据调用对象的不同,URL将为/something.htm或〜/something.htm

I have an object that requires the URL of a file that resides in the root of my web application. If this was an object that inherited from System.Web.Ui.Page I would just use the httpRequest object. However because this object does not I am uncertain how to get this url. Depending on the calling object, the url will be either /something.htm or ~/something.htm

有人可以给我指路吗?谢谢!

Can someone show me the way? Thanks!

-尼克

推荐答案

John正确了.如他所述,您可以/应该使用HttpContext.Current.Request对象.我认为您也只在寻找Url.换句话说,您不希望页面名称或查询字符串参数(如果存在).

John's got it right. You can/should use the HttpContext.Current.Request object as he stated. I think you are also looking for the Url up to the root only. In other words, you don't want the page name or query string params if they exist.

此例程有点令人讨厌,但它应该可以为您提供所需的内容.注意对HttpContext.Current.Request的引用.

This routine is a little obnoxious but it should give you what you need. Notice the reference to HttpContext.Current.Request.

private string UrlUpToRootWithNoPageReferenceOrQueryStringParameters()
{
    string Port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];

    if (Port == null || Port == "80" || Port == "443")
        Port = "";
    else
        Port = ":" + Port;

    string Protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];

    if (Protocol == null || Protocol == "0")
        Protocol = "http://";
    else
        Protocol = "https://";

    return Protocol + Context.Request.ServerVariables["SERVER_NAME"] + Port + Context.Request.ApplicationPath;
}

有较短的方法来获取您想要的东西,但是上面的例程仍然有效.如果您对更多内容感兴趣,请查看 Rick Strahl对ASP.NET的理解路径以获取更多信息.

There are shorter ways to get what you want, but again the routine above will work. If you're interested in more, check out Rick Strahl's Making Sense of ASP.NET Paths for more.

这篇关于从不继承System.Web.Ui.Page的对象获取文件的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆