How to get client ip address in asp.net core using c#?

Dung Do Tien May 19 2020 156

I am creating a website to read the news daily, I home page I have a box recommend news but I want to get news by user client IP, I try many ways but can not get exactly client Ip of the user. So how do I get the client IP address in asp.net core using c#?

Thanks for any suggestions.

Have 1 answer(s) found.
  • ANSWER:

    To get the client IP address in asp.net core, you need to get it from of request header because request header contains all information of the user including IP address.

    You need to create a short function as below:

    public static string GetClientIPAddress(HttpContext context)
    {
    	string ip = string.Empty;
    	if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
    	{
    		ip = context.Request.Headers["X-Forwarded-For"];
    	}
    	else
    	{
    		ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
    	}
    	return ip;
    } 
    

    GetClientIPAddress(context): This is a common function you can put it to some class statics to can reusable. This function will receipt into a HttpContext param.

     

    From your action of some controller you want to get client Ip, you can code as below:

    string clientIp = Utils.GetClientIPAddress(HttpContext);
    if (!string.IsNullOrEmpty(clientIp) && clientIp != "::1")
    {
        
         // To do something here
    	
    } 

    I hope short information is helpful to you. 

    Sandeep Kumar May 19 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips