如何在ASP.NET Web API中获取IpAddress和UserAgent方法

Yas*_*ser 22 asp.net-mvc asp.net-web-api

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

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

  • 来电者的IP
  • 来电者的用户代理
  • 来电者的二手网址

现在我在控制器中执行此操作时,我曾使用以下代码,

var ipAddress = Request.ServerVariables["REMOTE_ADDR"];
var userAgent = Request.UserAgent;
Run Code Online (Sandbox Code Playgroud)

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

任何人都可以帮我解决这个问题.

Yas*_*ser 21

我想到了,

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;
}
Run Code Online (Sandbox Code Playgroud)

在一点点帮助下

获取的ASP.NET Web API网页API消费者的IP地址和主机名 :

获取远程主机的IP地址

  • 我会尝试避免使用HttpContext,因为它只适用于WebHost. (6认同)
  • @DarrelMiller:由于这个问题多次出现,您认为Web API应该在HttpRequestMessage上有扩展来获取客户端IP地址吗?与System.Web.Http.WebHost和System.Web.Http.Owin.Selfhost一样,可以创建用户可以使用的请求消息扩展. (2认同)