Jag*_*ggu 175 c# asp.net uri httprequest
我想写一个小助手方法,它返回网站的基本URL.这就是我想出的:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}
Run Code Online (Sandbox Code Playgroud)
这有什么错误,你能想到吗?任何人都可以改进吗?
Fra*_*nby 316
试试这个:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
Run Code Online (Sandbox Code Playgroud)
War*_*ock 165
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
Run Code Online (Sandbox Code Playgroud)
而已 ;)
不幸的GetLeftPart是Uri,PCL版本不支持流行的解决方案.GetComponents但是,如果你需要可移植性,这应该可以解决问题:
uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
Run Code Online (Sandbox Code Playgroud)
对我来说,@ warlock看起来是迄今为止最好的答案,但我过去总是使用它;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Run Code Online (Sandbox Code Playgroud)
或者在WebAPI控制器中;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
Run Code Online (Sandbox Code Playgroud)
这很方便,因此您可以选择所需的转义格式.我不清楚为什么有两个这样的不同实现,并且据我所知,这个方法和@ warlock在这种情况下返回完全相同的结果,但它看起来GetLeftPart()也适用于非服务器Uri的mailto标签,例如.
我相信上面的答案并不考虑网站何时不在网站的根目录中.
这是一个WebApi控制器:
string baseUrl = (Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/')
+ HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;
Run Code Online (Sandbox Code Playgroud)
小智 5
我跟着去
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
225524 次 |
| 最近记录: |