开发者

ASP.NET MVC get current host

How do I get the host without using Request? This code can be placed in a controller:

return String.Equals(this.Request.Url.Host, absoluteUri.Host, StringComparison.Ordi开发者_开发百科nalIgnoreCase);

but I'm moving it out of a controller and need to find another way to replace this 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");
     }
}


You can use this outside of a controller:

System.Web.HttpContext.Current.Request.Url


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.


In the html helper you can use

    htmlHelper.ViewContext.HttpContext.Request.Url
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜