live-forum/server/webapi/LiveForum/LiveForum.Code/Utility/HttpContextExtensions.cs
2026-03-24 11:27:37 +08:00

65 lines
2.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiveForum.Code.Utility
{
/// <summary>
///
/// </summary>
public static class HttpContextExtensions
{
/// <summary>
/// 获取IP地址
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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();
}
/// <summary>
/// 从请求头中提取Authorization信息JWT
/// </summary>
/// <param name="headers">请求头字典。</param>
/// <returns>如果包含有效的Authorization头则返回JWT Token否则返回null。</returns>
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;
}
}
}