asp.net-mvc ASP.NET MVC 获取当前主机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4907422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC get current host
提问by Shawn Mclean
How do I get the host without using Request
? This code can be placed in a controller:
如何在不使用的情况下获得主机Request
?此代码可以放在控制器中:
return String.Equals(this.Request.Url.Host, absoluteUri.Host, StringComparison.OrdinalIgnoreCase);
but I'm moving it out of a controller and need to find another way to replace this this.Request.Url.Host
.
但我正在将它从控制器中移出,需要找到另一种方法来替换它this.Request.Url.Host
。
My whole purpose is to have access to this method in a helper class:
我的全部目的是在帮助类中访问此方法:
Url.IsLocalUrl(returnUrl);
My helper method will look like this:
我的辅助方法将如下所示:
public static string GetLocalUrl(string url)
{
if(Url.IsLocalUrl()){
return url;
}
else{
return Action("Security", "Home");
}
}
采纳答案by Vadim
Either use HttpContext.Current.Request
, or inject an instance of HttpContextBase
into whatever it is that needs this information. I would recommend option 2 because, you can then easily test this other component. Since HttpContextBase can be mocked/stubbed.
要么使用 HttpContext.Current.Request
,要么将 的实例注入HttpContextBase
到需要此信息的任何内容中。我会推荐选项 2,因为这样您就可以轻松测试其他组件。由于 HttpContextBase 可以被模拟/存根。
回答by santiagoIT
You can use this outside of a controller:
您可以在控制器之外使用它:
System.Web.HttpContext.Current.Request.Url
回答by syned
In the html helper you can use
在 html 助手中,您可以使用
htmlHelper.ViewContext.HttpContext.Request.Url