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

后端 未结 1 1057
我寻月下人不归
我寻月下人不归 2021-01-29 02: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条回答
  • 2021-01-29 02:52

    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.

    0 讨论(0)
提交回复
热议问题