如何在ASP.NET/C#中获取客户端设备信息? [英] How to get Client Device information in ASP.NET / C#?

查看:463
本文介绍了如何在ASP.NET/C#中获取客户端设备信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取访问日志的客户端计算机信息.如何在ASP.NET/C#中获取客户端设备名称和IP地址?

I am trying to get the client machine information for access log. How to get Client Device name and Ip address in ASP.NET / C#?

推荐答案

您可以从Request.UserHostAddress属性获取直接客户端IP:

You can get the direct client IP from the Request.UserHostAddress property:

public ActionResult Index()
{
    string ip = Request.UserHostAddress;
    ...
}

话虽这么说,但在许多情况下这可能还不够好.例如,假设您的Web服务器位于反向代理(例如nginx或HAProxy)的后面.在这种情况下,UserHostAddress将始终返回此代理的IP.如果要在这种情况下获取原始客户端IP地址,则可以使用标准的 这些反向代理服务器可能设置的请求标头:

This being said, there are many situations where this might not be good enough. Suppose for example that your web server is behind a reverse proxy such as nginx or HAProxy. In this case the UserHostAddress will always return the IP of this proxy. If you want to get the original client IP address in this situation you could use the standard X-Forwarded-For request header that those reverse proxy servers might set:

string ip = Request.Headers["X-Forwarded-For"];

还请注意,如果请求通过许多代理服务器,则X-Forwarded-For标头将代表每个代理服务器的IP地址的逗号分隔列表:

Also note that if the request goes through many proxy servers, then the X-Forwarded-For header will represent a comma separated list of IP addresses of each proxy server:

X-Forwarded-For: client, proxy1, proxy2

您可能需要考虑这种情况,如果要获取最接近或等于客户端的IP地址,则应从此列表中提取最左边的地址.

You might need to account for this situation and if you want to get the IP address that is closest or equal to the client then you should extract the leftmost address from this list.

就客户端设备名称"而言,TCP/HTTP协议中没有内置这种概念,因此,如果您希望能够检索它,则您的客户端可能需要使用一些自定义标头或参数来提供它在服务器上.

As far as the "Client Device name" is concerned, there's no such notion built into the TCP/HTTP protocol, so your client might need to supply it using some custom header or parameter if you want to be able to retrieve it on the server.

这篇关于如何在ASP.NET/C#中获取客户端设备信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆