using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiveForum.Code.Utility
{
///
///
///
public static class HttpContextExtensions
{
///
/// 获取IP地址
///
///
///
public static string GetClientIpAddress(this HttpContext context)
{
// 尝试从X-Forwarded-For头部中获取IP地址
var forwardedFor = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (!string.IsNullOrEmpty(forwardedFor))
{
// 处理可能的多个IP地址,通常第一个是客户端的真实IP
var ipAddresses = forwardedFor.Split(',');
if (ipAddresses.Length > 0)
{
return ipAddresses[0].Trim();
}
}
// 如果X-Forwarded-For头部不存在,使用RemoteIpAddress
return context.Connection.RemoteIpAddress?.ToString();
}
///
/// 从请求头中提取Authorization信息(JWT)。
///
/// 请求头字典。
/// 如果包含有效的Authorization头,则返回JWT Token,否则返回null。
public static string? GetAuthorization(this IHeaderDictionary headers)
{
// 尝试从请求头中获取Authorization字段
if (headers.TryGetValue("Authorization", out var authHeaderObj))
{
// 获取Authorization头的值并移除"Bearer "前缀
var authHeader = authHeaderObj.ToString();
// 如果Authorization以"Bearer "开头,提取JWT Token
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return authHeader.Substring(7).Trim(); // 直接返回JWT Token
}
}
// 如果没有Authorization头或格式不正确,返回null
return null;
}
}
}