How to get Client Device information in ASP.NET / C#?

陌路散爱 提交于 2021-02-05 11:11:28

问题


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#?


回答1:


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

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

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"];

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

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.

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.



来源:https://stackoverflow.com/questions/42733402/how-to-get-client-device-information-in-asp-net-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!