How ASP. NET core obtains client IP address under load Balancing scenario

Source: Internet
Author: User
Tags servervariables

In ASP. NET, when using load balancing, the IP address of the client can be obtained through ServerVariables.

var ip = Request. servervariables["http_x_forwarded_for"];

However, there is no corresponding implementation of ServerVariables in ASP. Can be obtained in the HttpContext.Request.Headers, it is important to note that the key is not the same as the ServerVariables way, ServerVariables is "http_x_forwarded_for", HttpContext.Request.Headers is "x-forwarded-for", the sample code is as follows:

var ip = context. request.headers["x-forwarded-for"]. FirstOrDefault ();

The complete extension method is implemented as follows:

 Public Static classhttpcontextextension{ Public Static stringGetuserip ( ThisHttpContext context) {        varIP = context. request.headers["x-forwarded-for"].        FirstOrDefault (); if(string. IsNullOrEmpty (IP)) {IP=context.        Connection.RemoteIpAddress.ToString (); }        returnIP; }}

How ASP. NET core obtains client IP address under load Balancing scenario

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.