Reputation: 313
I have developed a web application that is deployed as a web app on Azure.
I need to get the client's IP address such that I can use a GeoIP API to get the country from which the client is connecting.
So here's my question, how can I get the client's IP address when they send a request to view the homepage? I am using ASP.NET MVC.
Upvotes: 9
Views: 5513
Reputation: 702
I'm doing it in a filter with Azure and .NET6: -
using Microsoft.AspNetCore.Mvc.Filters;
namespace MyProject.Filters
{
public class CustomActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var visitorIp = context.HttpContext.Connection.RemoteIpAddress.ToString();
}
}
}
Upvotes: 0
Reputation: 43193
Try this (verified on an Azure Web App using ASP.NET Core 2.x):
using Microsoft.AspNetCore.Http.Features;
using System.Net;
....
var connection = HttpContext.Features.Get<IHttpConnectionFeature>();
IPAddress clientIP = connection.RemoteIpAddress;
Upvotes: 10