Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.OrdinalIgnoreCase);

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");
     }
}
like image 776
Shawn Mclean Avatar asked Feb 05 '11 14:02

Shawn Mclean


2 Answers

You can use this outside of a controller:

System.Web.HttpContext.Current.Request.Url
like image 171
santiagoIT Avatar answered Sep 19 '22 13:09

santiagoIT


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.

like image 44
Vadim Avatar answered Sep 21 '22 13:09

Vadim