asp.net – 如何获取网站根URL?
发布时间:2020-12-15 19:08:27 所属栏目:asp.Net 来源:网络整理
导读:我想动态获取ASP.NET应用程序的绝对根Url。这需要是以下形式的应用程序的完整根网址:http(s):// hostname(:port)/ 我一直在使用这个静态方法: public static string GetSiteRootUrl(){ string protocol; if (HttpContext.Current.Request.IsSecureConnec
我想动态获取ASP.NET应用程序的绝对根Url。这需要是以下形式的应用程序的完整根网址:http(s):// hostname(:port)/
我一直在使用这个静态方法: public static string GetSiteRootUrl() { string protocol; if (HttpContext.Current.Request.IsSecureConnection) protocol = "https"; else protocol = "http"; StringBuilder uri = new StringBuilder(protocol + "://"); string hostname = HttpContext.Current.Request.Url.Host; uri.Append(hostname); int port = HttpContext.Current.Request.Url.Port; if (port != 80 && port != 443) { uri.Append(":"); uri.Append(port.ToString()); } return uri.ToString(); } 但是,如果我没有HttpContext.Current在范围内? 解决方法
对于WebForms,此代码将返回应用程序根目录的绝对路径,无论应用程序嵌套的方式如何:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/") 上面的第一部分返回没有尾部斜杠的应用程序(http:// localhost)的方案和域名。 ResolveUrl代码返回应用程序根目录(/ MyApplicationRoot /)的相对路径。通过将它们组合在一起,您可以获得Web表单应用程序的绝对路径。 使用MVC: HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/") 或者,如果您尝试直接在Razor视图中使用它: @HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 基于多个(但不是全部)条件的IIS重定向规则
- AutoMapper在asp.net core的使用
- ASP.NET自定义控件
- ASP.net缓存绝对到期不工作
- asp.net – AspNetCore.Mvc与AspNetCore.Mvc.Core
- asp.net-mvc – 如何将模型传递给部分视图
- asp.net-mvc-3 – 用Response调用的Ajax.BeginForm OnFailu
- asp.net – aspx中__EVENTVALIDATION __VIEWSTATE的目的是什
- asp.net-mvc – 当它被称为DocumentationController时,MVC控
- asp.net-mvc – 使用javascript的Mvc ActionLink
推荐文章
站长推荐
热点阅读