ASP.NET Core中如何校验Cookie通过后跳转至首页或原请求URL
逻辑放置位置说明
- 这类全局请求拦截逻辑不要写在Controller中,会产生大量重复编码
- .NET 6已经合并了原Startup.cs的配置逻辑到
Program.cs文件,你可以通过自定义中间件实现全局Cookie校验,这是当前场景最合理的实现方案
完整实现步骤
步骤1:在Program.cs中配置Cookie校验中间件
注意中间件的注册顺序,需要放在静态文件中间件之后、路由中间件之后、端点执行之前,同时要排除静态资源、Cookie同意页本身的请求,避免出现重定向死循环。
var builder = WebApplication.CreateBuilder(args); // 如果你用Razor Page则替换为AddRazorPages() builder.Services.AddControllersWithViews(); var app = builder.Build(); // 静态文件中间件放在最前面,避免CSS/JS等静态资源触发重定向 app.UseStaticFiles(); app.UseRouting(); // 自定义Cookie校验中间件 app.Use(async (context, next) => { // 可自行调整配置项 const string AGREE_COOKIE_NAME = "banneracceptance"; string agreePagePath = "/Home/CookieAgree"; string defaultHomePath = "/Home/Index"; // 排除无需校验的请求:同意页、API接口、带后缀的静态资源 if (context.Request.Path.StartsWithSegments(agreePagePath) || context.Request.Path.StartsWithSegments("/api") || context.Request.Path.Value?.Contains(".") == true) { await next(); return; } // 校验是否已存在同意Cookie bool hasAgreed = context.Request.Cookies.TryGetValue(AGREE_COOKIE_NAME, out string cookieVal) && bool.TryParse(cookieVal, out bool agreed) && agreed; if (hasAgreed) { // 已同意,继续执行后续请求逻辑 await next(); return; } // 未同意,将当前访问地址编码后传给同意页,后续完成同意后跳转回原地址 string returnUrl = context.Request.Path + context.Request.QueryString; if (string.IsNullOrWhiteSpace(returnUrl) || returnUrl == "/") { returnUrl = defaultHomePath; } context.Response.Redirect($"{agreePagePath}?returnUrl={Uri.EscapeDataString(returnUrl)}"); }); app.UseAuthorization(); // 路由配置,用Razor Page则替换为MapRazorPages() app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
步骤2:实现Cookie同意页处理逻辑
以MVC架构为例,在HomeController中添加同意页相关的处理方法:
public class HomeController : Controller { // 同意页GET请求处理 public IActionResult CookieAgree(string returnUrl) { ViewBag.ReturnUrl = returnUrl ?? Url.Action("Index"); return View(); } // 用户点击同意后的POST请求处理 [HttpPost] public IActionResult AgreeCookie(string returnUrl) { // 写入同意Cookie,过期时间可自行调整,示例为1年 var cookieOptions = new CookieOptions { Expires = DateTimeOffset.Now.AddYears(1), HttpOnly = true, // 禁止前端JS篡改,提升安全性 Secure = Request.IsHttps }; Response.Cookies.Append("banneracceptance", "true", cookieOptions); // 校验跳转地址合法性,避免恶意钓鱼跳转 if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } // 地址不合法则跳转到首页 return RedirectToAction("Index"); } public IActionResult Index() { return View(); } }
步骤3:编写同意页前端(CookieAgree.cshtml)
<form method="post" asp-action="AgreeCookie"> <input type="hidden" name="returnUrl" value="@ViewBag.ReturnUrl" /> <p>我们需要使用Cookie提升您的使用体验,同意Cookie政策后即可继续访问</p> <button type="submit">同意并继续</button> </form>
内容的提问来源于stack exchange,提问作者Munchkin
相关产品推荐
相关产品推荐

