Getting HttpRequest.IsLocal/Ip-Address/Port in ASP.NET Core and MVC 6
Introduction:
HttpContext(which own HttpRequest and HttpResponse objects) in ASP.NET Core is much subtler than the previous HttpContext which is defined in System.Web. But you might find some properties/methods of HttpContext/HttpRequest/HttpResponse classes are missing in ASP.NET Core which are available in old HttpContext world, e.g. IsLocal property. Fortunately, ASP.NET Core is OWIN complaint. This means that we can easily access OWIN environment dictionary which include very important information about request, response and server. In this article, I will show you how to access this OWIN environment dictionary and I will also create IsLocal, GetRemoteIpAddress and GetPort request extension methods.
Description:
Assuming that you are running Visual Studio 2015 and you have created an ASP.NET vNext Mvc application. First open project.json and include Microsoft.AspNet.Owin package in dependencies section. Then add these extension methods,
public static class HttpRequestExtensions { public static bool IsLocal(this HttpRequest request) { IDictionary<string, object> env = new OwinEnvironment(request.HttpContext); return (bool)env["server.IsLocal"]; } public static string GetRemoteIpAddress(this HttpRequest request) { IDictionary<string, object> env = new OwinEnvironment(request.HttpContext); return env["server.RemoteIpAddress"]?.ToString(); } public static string GetPort(this HttpRequest request) { IDictionary<string, object> env = new OwinEnvironment(request.HttpContext); return env["server.LocalPort"]?.ToString(); } }
Note that I am simply creating an instance of OwinEnvironment, passing HttpRequest.HttpConext in parameter. From this OWIN environment dictionary, I am retrieving server.IsLocal server.RemoteIpAddress and server.LocalPort values. In addition to these, there are other environment data you access from this dictionary. You can find a list of keys at here.
Update: There is another better way to find this information. Check Getting the Client’s IP Address in ASP.NET vNext Web Applications.
Summary:
ASP.NET Core support OWIN(also called sucesser of katana project). Means we can easily access OWIN environment dictionary. In this article I showed you how to access this.