22

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.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281

2 Answers2

21

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 Web API &

Get the IP address of the remote host

Community
  • 1
  • 1
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • 6
    I would try and avoid HttpContext as it only works in WebHost. – Darrel Miller Jun 28 '13 at 15:02
  • 2
    @DarrelMiller: Since this question has come up many times, do you think Web API should have an extension on HttpRequestMessage to get the client IP address? Like the System.Web.Http.WebHost and System.Web.Http.Owin.Selfhost can create request message extensions which users could use. – Kiran Jun 28 '13 at 17:28
  • @KiranChalla It would be a fairly low impact change that would definitely help a lot of people. – Darrel Miller Jun 28 '13 at 17:54
  • @DarrelMiller: Sure, created an issue here: https://aspnetwebstack.codeplex.com/workitem/1116 – Kiran Jun 28 '13 at 18:18
  • How-to add System.Web to NET 6 Minimal API ? good pattern ? – Kiquenet May 31 '22 at 14:48
4

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

Read more:

Community
  • 1
  • 1
YD1m
  • 5,845
  • 2
  • 19
  • 23