namespace Dpz.Core.Web.Library.Middleware;
/// <summary>
/// 处理HTTP响应中间件
/// </summary>
public class HttpResponseHeaderHandel
{
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public HttpResponseHeaderHandel(RequestDelegate next)
{
_next = next;
}
/// <summary>
///
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public async Task Invoke(HttpContext httpContext)
{
/*
* from https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
* 列出哪些 http response headers 对外暴露
* 这里设置为所有
*/
httpContext.Response.Headers.Append("Access-Control-Expose-Headers", "*");
var sessionId = httpContext.Request.Cookies[Program.AuthorizeCookieName + ".SessionId"];
if (string.IsNullOrWhiteSpace(sessionId))
{
httpContext.Response.Cookies.Append(
Program.AuthorizeCookieName + ".SessionId",
Guid.NewGuid().ToString("N"),
new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict,
IsEssential = true,
Expires = DateTimeOffset.Now.AddYears(1),
}
);
}
await _next.Invoke(httpContext);
}
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
这是一个ASP.NET Core中间件类,主要用于处理HTTP响应头和会话管理。让我详细解释一下这个代码:
类的作用
HttpResponseHeaderHandel 是一个自定义的HTTP中间件,用于在每个HTTP请求处理过程中执行两个主要任务:
- 设置CORS响应头
- 管理会话Cookie
代码结构分析
构造函数
public HttpResponseHeaderHandel(RequestDelegate next)
{
_next = next;
}
- 接收下一个中间件的委托
RequestDelegate - 这是ASP.NET Core中间件的标准模式,形成中间件管道
核心处理方法 Invoke
1. CORS头设置
httpContext.Response.Headers.Append("Access-Control-Expose-Headers", "*");
- 设置
Access-Control-Expose-Headers为* - 这允许前端JavaScript访问所有的HTTP响应头
- 通常用于跨域请求场景
2. 会话Cookie管理
var sessionId = httpContext.Request.Cookies[Program.AuthorizeCookieName + ".SessionId"];
if (string.IsNullOrWhiteSpace(sessionId))
{
// 创建新的SessionId Cookie
}
Cookie创建逻辑:
- 检查是否存在名为
{AuthorizeCookieName}.SessionId的Cookie - 如果不存在,则创建一个新的SessionId Cookie
- 使用
Guid.NewGuid().ToString("N")生成唯一标识符
Cookie安全配置:
HttpOnly = true:防止JavaScript访问,增强安全性Secure = true:仅在HTTPS连接中传输SameSite = SameSiteMode.Strict:严格的同站点策略,防止CSRF攻击IsEssential = true:标记为必要Cookie,即使用户拒绝非必要Cookie也会保留Expires = DateTimeOffset.Now.AddYears(1):设置1年过期时间
使用场景
这个中间件适用于:
- 需要跨域访问响应头的Web应用
- 需要持久化会话标识的系统
- 对安全性有较高要求的应用(通过严格的Cookie配置)
注意事项
Program.AuthorizeCookieName需要在其他地方定义- 中间件需要在Startup或Program.cs中注册才能生效
Secure = true要求应用运行在HTTPS环境下
这是一个设计良好的中间件,兼顾了功能性和安全性。
评论加载中...