server {
listen 80;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:5000; }
}
public static class GetHostIP
{
/// <summary>
/// 获取客户Ip
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetClientUserIp(this HttpContext context)
{
var userHostAddress = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = context.Connection.RemoteIpAddress.ToString();//这个是直接IP,如果经过反向代理IP会变成代理机的,如果代理机就是本机就会变成127.0.0.1
}
//最后判断获取是否成功,并检查IP地址的格式
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
/// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
}
补充说明
HttpContext 对象
1.在Mvc 控制器实例中包含了上下文对象,可以直接使用
2.使用IHttpContextAccessor接口获取HttpContext对象
2.1我们先要将它注册到ServiceCollection中,否则无法获取到这个对象。
public void ConfigureServices(IServiceCollection services) {
//services.AddHttpContextAccessor(); services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
2.3使用时,手动获取对象
public class TestClass { public static IServiceProvider ServiceProvider; public static HttpContext GetContext() { object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor)); HttpContext context = ((IHttpContextAccessor)factory).HttpContext; return context; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。