一、通过静态扩展方法
1、写个扩展方法在控制器里面:注:不能创建外部类,否则会报错,HttpContext必须是和带有继承ControllerBase的类一起才行
namespace WebAPI.Controllers
{
public static class Extension
{
/// <summary>
/// 获取客户Ip
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetClientUserIp(this HttpContext context)
{
var ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.ToString();
}
return ip;
}
}
/// <summary>
/// 首页控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
public HomeController()
{
}
[HttpGet]
public string Index()
{
var ip = HttpContext.GetClientUserIp();
return ip;
}
}
}
二、通过注入服务方式
1.在Startup.cs文件里注入服务:文章来源:https://www.toymoban.com/news/detail-770733.html
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc();
//注入Http
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
2、去控制器里面写入:文章来源地址https://www.toymoban.com/news/detail-770733.html
/// <summary>
/// 首页控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
//声明
private readonly IHttpContextAccessor httpContextAccessor;
public HomeController(IHttpContextAccessor IHttpContextAccessor)
{
this.httpContextAccessor = IHttpContextAccessor;
}
[HttpGet]
public string Index()
{
string ip = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
//string ip = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
return ip;
}
}
到了这里,关于.net core WebAPI 获取客户端IP的地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!