Suleman
Suleman

Reputation: 712

How to get user IP address in API model in ASP.NET Core 2.1?

I am not having issue getting user IP address while the code is running in web API controller but in model I am actually unable to use:

this.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

The reason I need need user IP because I need to geolocate its country by comparing it via data available from a third party provider. I could do this during web API controller phase but it is better to have in model, this way I can create a custom annotation to do my job as I will need to reuse the code in several models.

Upvotes: 1

Views: 2894

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

You're breaking SOLID here. It's not appropriate for you model to know about HttpContext or how to retrieve a remote IP address from that. The logic you want to encapsulate in your model simply needs an IP address, so that is what you should give it. This can either be provided in the constructor of your model class or just as a param to the particular method(s) that need to utilize it. For example, create a method like:

public void GeolocateByIP(string ip)
{
    // do geolocation
}

In your controller action, then, you simply do something like:

model.GeolocateByIP(HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString());

Upvotes: 4

Tech Yogesh
Tech Yogesh

Reputation: 447

You can access HttpContext by injecting IHttpContextAccesor in asp.net core.

public class ModelClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ModelClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
}

Upvotes: 0

Related Questions