【新增】增加获取用户真实ip地址中间件【RealIpMiddleware】,防止Nginx转发后只能获取服务器ip的问题。

This commit is contained in:
jianweie code
2023-10-18 23:39:30 +08:00
parent f6cc3707f7
commit 05309204e6
4 changed files with 47 additions and 1 deletions

View File

@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 获取真实ip地址
/// </summary>
public class RealIpMiddleware
{
private readonly RequestDelegate _next; public RealIpMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
var headers = context.Request.Headers;
if (headers.ContainsKey("X-Forwarded-For"))
{
context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]);
}
return _next(context);
}
}
}