How to get IpAddress and UserAgent in ASP.NET Web API get methods

[Originally Posted By]: http://stackoverflow.com/questions/17364801/how-to-get-ipaddress-and-useragent-in-asp-net-web-api-get-methods

I am using ASP.NET Web Api to expose a few GET methods.

But before I return the data I need to log a couple of details to the db, of which few of them are as listed below :

  • Caller’s Ip
  • Caller’s User Agent
  • Caller’s Used Url

Now in the controller when I used to do this I used to use the following code,

var ipAddress = Request.ServerVariables["REMOTE_ADDR"];
var userAgent = Request.UserAgent;

But here in Web API I am unable to use this.

Can anyone please help me out with this.

shareedit

I figured it out,

public static LogModel GetApiLogDetails()
{
    var logModel = new LogModel();
    logModel.TimeStamp   = DateTime.Now;
    logModel.CallerIp    = HttpContext.Current.Request.UserHostAddress;
    logModel.CallerAgent = HttpContext.Current.Request.UserAgent;
    logModel.CalledUrl   = HttpContext.Current.Request.Url.OriginalString;
    return logModel;
}

with a little help from

Get Web Api consumer IP Address and HostName in ASP.net C# &

Get the IP address of the remote host

shareedit

You should use HttpRequestMessage class, that conteins all data you need.

Read more:

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s