【问题标题】:How to get IpAddress and UserAgent in ASP.NET Web API get methods如何在 ASP.NET Web API get 方法中获取 IpAddress 和 UserAgent
【发布时间】:2013-06-26 05:34:53
【问题描述】:

我正在使用 ASP.NET Web Api 来公开一些 GET 方法。

但在我返回数据之前,我需要将一些详细信息记录到数据库中,其中很少有如下所列:

  • 来电者的IP
  • 调用者的用户代理
  • 调用者使用的网址

现在在控制器中,当我以前这样做时,我曾经使用以下代码,

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

但是在 Web API 中我无法使用它。

谁能帮帮我。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    您应该使用HttpRequestMessage 类,它包含您需要的所有数据。

    阅读更多:

    【讨论】:

      【解决方案2】:

      我想通了,

      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;
      }
      

      的帮助下

      Get Web Api consumer IP Address and HostName in ASP.NET Web API &

      Get the IP address of the remote host

      【讨论】:

      • 我会尽量避免使用 HttpContext,因为它只适用于 WebHost。
      • @DarrelMiller:既然这个问题已经出现很多次了,你认为Web API应该在HttpRequestMessage上有一个扩展来获取客户端IP地址吗?像 System.Web.Http.WebHost 和 System.Web.Http.Owin.Selfhost 可以创建用户可以使用的请求消息扩展。
      • @KiranChalla 这将是一个影响相当小的变化,肯定会帮助很多人。
      • @DarrelMiller:当然,在这里创建了一个问题:aspnetwebstack.codeplex.com/workitem/1116
      猜你喜欢
      • 2021-07-11
      • 2019-01-27
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多