无需使用〜即可查找应用程序根URL

时间:2009-04-29 11:52:07

标签: asp.net

我需要在String中构建页面的URL,向其发送电子邮件(作为电子邮件验证系统的一部分)。如果我使用〜符号表示应用程序根,则按字面意思理解。

该应用程序将部署在三个不同站点(位于不同端口)的服务器上,每个站点可通过2个不同的URL(一个用于LAn,一个用于Internet)访问。

因此对URL进行硬编码是不可能的。我想在我的应用程序

中构建verify.aspx的url

请帮忙

7 个答案:

答案 0 :(得分:13)

你需要这个:

HttpContext.Current.Request.ApplicationPath

它相当于URL中的“〜”。

http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx

答案 1 :(得分:13)

很遗憾,列出的所有方法都没有从http://---开始生成完整的网址。

所以我不得不从request.url中提取这些内容。像这样的东西

Uri url=HttpContext.Current.Request.Url;
StringBuilder urlString = new StringBuilder();
urlString.Append(url.Scheme);
urlString.Append("://");
urlString.Append(url.Authority);
urlString.Append("/MyDesiredPath");

有人可以发现任何潜在的问题吗?

答案 2 :(得分:3)

尝试:

HttpRequest req = HttpContext.Current.Request;
string url = req.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)
    + ((req.ApplicationPath.Length > 1) ? req.ApplicationPath : "");

答案 3 :(得分:2)

您需要将URL作为Web应用程序配置的一部分。 Web应用程序不知道如何从外部传播它。

E.g。考虑一个场景,在你的网络服务器前面有多个代理和负载均衡器......除了自己的IP外,网络服务器怎么知道呢?

因此,您需要通过添加基本网址来配置Web应用程序的每个实例,例如作为其web.config中的应用程序设置。

答案 4 :(得分:0)

您可以使用HttpRequest.RawURL(docs here)属性并在此基础上建立您的URL,但如果您支持任何类型的重定向,则RawURL可能无法反映您的应用程序的实际URL。 / p>

答案 5 :(得分:0)

我最终得到了这个。我接受请求url,并使用Request.ApplicationRoot的位置来发现uri的左侧部分。应该使用虚拟目录“/ example”或根目录“/".

中托管的应用程序
    private string GetFullUrl(string relativeUrl)
    {
        if (string.IsNullOrWhiteSpace(relativeUrl)) 
            throw new ArgumentNullException("relativeUrl");

        if (!relativeUrl.StartsWith("/"))
            throw new ArgumentException("url should start with /", "relativeUrl");

        string current = Request.Url.ToString();
        string applicationPath = Request.ApplicationPath;
        int applicationPathIndex = current.IndexOf(applicationPath, 10, StringComparison.InvariantCultureIgnoreCase);

        // should not be possible
        if (applicationPathIndex == -1) throw new InvalidOperationException("Unable to derive root path");

        string basePath = current.Substring(0, applicationPathIndex);
        string fullRoot = string.Concat(
            basePath,
            (applicationPath == "/") ? string.Empty : applicationPath,
            relativeUrl);

        return fullRoot;
    }

答案 6 :(得分:0)

这一直对我有用:

string root = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "");