asp.net-mvc 如何在 ASP.NET Web API 获取方法中获取 IpAddress 和 UserAgent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17364801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get IpAddress and UserAgent in ASP.NET Web API get methods
提问by Yasser Shaikh
I am using ASP.NET Web Api to expose a few GET methods.
我正在使用 ASP.NET Web Api 来公开一些 GET 方法。
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
- 来电者的IP
- 呼叫者的用户代理
- 来电者使用的网址
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.
但是在 Web API 中,我无法使用它。
Can anyone please help me out with this.
任何人都可以帮我解决这个问题。
采纳答案by Yasser Shaikh
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&
在 ASP.NET Web API 中获取 Web Api 消费者 IP 地址和主机名&
回答by YD1m
You should use HttpRequestMessageclass, that conteins all data you need.
您应该使用HttpRequestMessage包含您需要的所有数据的类。
Read more:
阅读更多:

