Created
May 10, 2012 14:36
-
-
Save MikeJansen/2653453 to your computer and use it in GitHub Desktop.
HttpRequestMessage.GetClientIpAddress for ASP.NET MVC 4 / Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original idea: http://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host | |
using System.Net.Http; | |
using System.ServiceModel.Channels; | |
using System.Web; | |
namespace CrowSoftware.Api | |
{ | |
public static class HttpRequestMessageHelper | |
{ | |
public static string GetClientIpAddress(this HttpRequestMessage request) | |
{ | |
if (request.Properties.ContainsKey("MS_HttpContext")) | |
{ | |
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; | |
} | |
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) | |
{ | |
RemoteEndpointMessageProperty prop; | |
prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; | |
return prop.Address; | |
} | |
else | |
{ | |
return null; | |
} | |
} | |
} | |
} |
UserHostName '((((HttpContextBase)request.Properties["MS_HttpContext"])).Request).UserHostName' threw an exception of type 'System.ArgumentException' string {System.ArgumentException}
I'm having same problem with Argument exception. It happens when I wrap the code in Task.Run(... )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UserHostName '((((HttpContextBase)request.Properties["MS_HttpContext"])).Request).UserHostName' threw an exception of type 'System.ArgumentException' string {System.ArgumentException}