专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

C#.NET6 ASP.NET CORE MVC 获取客户端IP

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:11:54       共计:3641 浏览

重点是拿到HttpContext 对象。


先从Headers["Cdn-Src-Ip"] 中取IP,其次从Headers["X-Forwarded-For"] 取,最后从context.Connection.RemoteIpAddress 中取。


有可能遇到“::ffff:192.168.2.131” 这种IP,把"::ffff:"Replace掉。




工具类CoreMvcClientIpUtil:

复制代码


namespace CommonUtils

{

   public static class CoreMvcClientIpUtil

   {

       public static string GetClientIP(HttpContext context)

       {

           var ip = context.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();

           if (!string.IsNullOrEmpty(ip))

               return IpReplace(ip);


           ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();

           if (!string.IsNullOrEmpty(ip))

               return IpReplace(ip);


           ip = context.Connection.RemoteIpAddress.ToString();


           return IpReplace(ip);

       }


       static string IpReplace(string inip)

       {

           //::ffff:

           //::ffff:192.168.2.131 这种IP处理

           if (inip.Contains("::ffff:"))

           {

               inip = inip.Replace("::ffff:", "");

           }

           return inip;

       }


   }

}


复制代码






一、使用HttpContextAccessor


在Program.cs中增加一行:


//获取IP使用

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

复制代码


var builder = WebApplication.CreateBuilder(args);


// Add services to the container.

builder.Services.AddControllersWithViews();


//获取IP使用

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


var app = builder.Build();


// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment())

{

   app.UseExceptionHandler("/Home/Error");

}

app.UseStaticFiles();


app.UseRouting();


app.UseAuthorization();


app.MapControllerRoute(

   name: "default",

   pattern: "{controller=Home}/{action=Index}/{id?}");


app.Run();


复制代码


修改Controller:


全局变量增加


private readonly IHttpContextAccessor _httpContextAccessor;


构造函数增加


_httpContextAccessor = httpContextAccessor;


Action中获取IP


var ip = CoreMvcClientIpUtil.GetClientIP(_httpContextAccessor.HttpContext);



复制代码


using CommonUtils;

using CommonUtils.Extensions;

using Microsoft.AspNetCore.Mvc;


namespace AspNetCoreMvcClientIp2.Controllers

{

   public class OkController : Controller

   {

       private readonly IHttpContextAccessor _httpContextAccessor;


       public OkController(IHttpContextAccessor httpContextAccessor)

       {

           _httpContextAccessor = httpContextAccessor;

       }

       // GET: OkController

       public ActionResult Index()

       {

           var ip = CoreMvcClientIpUtil.GetClientIP(_httpContextAccessor.HttpContext);

           ViewBag.myip1 = "ip:" + ip;


           //直接实例化HttpContextAccessor

           IHttpContextAccessor ih = new HttpContextAccessor();

           string ip2 = CoreMvcClientIpUtil.GetClientIP(ih.HttpContext);

           ViewBag.myip2 = "ip2:" + ip2;


           //使用ControllerBase的HttpContext

           var ip3 = CoreMvcClientIpUtil.GetClientIP(HttpContext);

           ViewBag.myip3 = "ip3:" + ip3;


           //扩展方法

           var ip4 = HttpContext.GetClientIP();

           ViewBag.myip4 = "ip4:" + ip4;


           return View();

       }


       

   }

}


复制代码






也可以直接实例化HttpContextAccessor:


IHttpContextAccessor ih = new HttpContextAccessor();

           string ip2 = CoreMvcClientIpUtil.GetClientIP(ih.HttpContext);






二、使用ControllerBase的HttpContext


//使用ControllerBase的HttpContext

           var ip3 = CoreMvcClientIpUtil.GetClientIP(HttpContext);

           ViewBag.myip3 = "ip3:" + ip3;






三、扩展HttpContext



复制代码


using Microsoft.AspNetCore.Http;


namespace CommonUtils.Extensions

{

   public static class HttpContextExtension

   {

       public static string GetClientIP(this HttpContext context)

       {

           var ip = context.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();

           if (!string.IsNullOrEmpty(ip))

               return IpReplace(ip);


           ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();

           if (!string.IsNullOrEmpty(ip))

               return IpReplace(ip);


           ip = context.Connection.RemoteIpAddress.ToString();


           return IpReplace(ip);

       }


       static string IpReplace(string inip)

       {

           //::ffff:

           //::ffff:192.168.2.131 这种IP处理

           if (inip.Contains("::ffff:"))

           {

               inip = inip.Replace("::ffff:", "");

           }

           return inip;

       }

   }

}


复制代码






在Controller中使用时要using CommonUtils.Extensions;


var ip4 = HttpContext.GetClientIP();

           ViewBag.myip = "ip4:" + ip4;



版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:.Net 5/6.0 根目录静态文件设置 | ·下一条:Asp.Net Core 发布IIS报错 HTTP Error 500.30 - ASP.NET Core app failed to start

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有