c# - Request.Url.Host 和 ApplicationPath 一次调用

标签 c# asp.net code-behind httpcontext

有没有办法在一次调用中获取 HttpContext.Current.Request.Url.HostHttpContext.Current.Request.ApplicationPath

像“完整的应用程序 url”之类的东西?

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

http://[www.mysite.com/mywebapp]/Pages/Default.aspx

我只是出于好奇才问的。

编辑 2:感谢所有回复,但没有一个正是我要找的。 仅供引用,我通过这种方式解决了问题(但我仍然想知道是否有更流畅的方法):

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

最佳答案

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

关于c# - Request.Url.Host 和 ApplicationPath 一次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/689678/

相关文章:

c# - 如何解决Azure “Windows logins are not supported in this version of SQL Server”?

asp.net - 如何解码 RDP 服务器的远程资源 URL (webfeed.aspx) 中返回的数据?

c# - 使用二进制格式写入和读取对象,u-sql

jquery - 更改asp :label with jQuery then access in codebehind

c# - 将 IList 转换为 SomeType[]

c# - Process.Start(url) 失败

c# - 在 C# 中将数据加载到 DataTable 会出现 "Unknown SQL type - 0"错误

asp.net - 使用 Rake 创建 IIS 网站

javascript - session 结束时如何从 Global.asax 重定向到 login.aspx 页面

c# - 当前上下文中不存在名称 'controlname'