首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在一个呼叫中使用Request.Url.Host和ApplicationPath

在一个呼叫中使用Request.Url.Host和ApplicationPath
EN

Stack Overflow用户
提问于 2009-03-27 13:01:05
回答 6查看 75.8K关注 0票数 18

有没有办法让HttpContext.Current.Request.Url.HostHttpContext.Current.Request.ApplicationPath在一个调用中呢?

比如“完整的应用程序url"?

编辑:澄清-我需要的是[]中的这一部分:

代码语言:javascript
复制
http://[www.mysite.com/mywebapp]/Pages/Default.aspx

我只是出于好奇才问的。

编辑2:感谢你的回复,但没有一个是我想要的。仅供参考,我用这种方法解决了这个问题(但我仍然有兴趣知道是否有更平滑的方法):

代码语言:javascript
复制
public string GetWebAppRoot()
{
    if(HttpContext.Current.Request.ApplicationPath == "/")
        return "http://" + HttpContext.Current.Request.Url.Host;
    else
        return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-03-27 14:06:56

代码语言:javascript
复制
public static string GetSiteRoot()
{
  string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
  if (port == null || port == "80" || port == "443")
    port = "";
  else
    port = ":" + port;

  string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
  if (protocol == null || protocol == "0")
    protocol = "http://";
  else
    protocol = "https://";

  string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;

  if (sOut.EndsWith("/"))
  {
    sOut = sOut.Substring(0, sOut.Length - 1);
  }

  return sOut;
}
票数 32
EN

Stack Overflow用户

发布于 2009-09-28 01:53:42

这在使用端口号的本地主机上不起作用,所以做了一些小的修改:

代码语言:javascript
复制
  private string GetWebAppRoot()
    {
        string host = (HttpContext.Current.Request.Url.IsDefaultPort) ? 
            HttpContext.Current.Request.Url.Host : 
            HttpContext.Current.Request.Url.Authority;
        host = String.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, host);            
        if (HttpContext.Current.Request.ApplicationPath == "/")
            return host;
        else
            return host + HttpContext.Current.Request.ApplicationPath;
    }
票数 18
EN

Stack Overflow用户

发布于 2009-08-19 13:46:35

你真正应该做的是:

代码语言:javascript
复制
return String.Format("{0}://{1}/", Request.Url.Scheme, Request.Url.Host);

如果您使用的是HTTPS (或其他模式!)

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/689678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档