.NET Core 2中移除URL内?ReturnUrl=参数的实现方法
如何阻止ASP.NET Core应用添加"?ReturnUrl="参数
首先得捋清楚:ReturnUrl参数通常是ASP.NET Core的认证中间件(比如Cookie认证)在重定向到登录页时自动加上的,用来记录用户原本要访问的页面。你之前写的中间件没生效,大概率是时机不对——你是在请求进来时检查QueryString,但这个参数是在响应重定向时被添加到Location头里的,请求阶段根本看不到它,自然没法处理。
下面给你两种可行的解决方案,按需选择:
方案一:从源头禁用(推荐)
直接通过认证配置,让中间件不要添加ReturnUrl参数,这是最高效的方式。以Cookie认证为例,在ConfigureServices里修改配置:
using Microsoft.AspNetCore.Authentication.Cookies; services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { // 方式1:直接清空ReturnUrl参数名,让中间件不再添加 options.ReturnUrlParameter = string.Empty; // 方式2:自定义重定向逻辑,完全控制跳转URL options.Events = new CookieAuthenticationEvents { OnRedirectToLogin = context => { // 直接重定向到登录页,不带任何额外参数 context.Response.Redirect("/Account/Login"); return Task.CompletedTask; } }; });
如果用的是其他认证方式(比如JWT、OpenID Connect),也可以找到对应的配置项来禁用ReturnUrl的生成。
方案二:用中间件拦截重定向响应
如果不想修改认证配置,或者需要处理其他中间件生成的ReturnUrl,可以写一个中间件在响应阶段拦截重定向,移除URL里的ReturnUrl参数:
中间件代码
using System.Web; // 需要引用System.Web.HttpUtility,也可替换为.NET Core的QueryHelpers public class RemoveReturnUrlMiddleware { private readonly RequestDelegate _next; public RemoveReturnUrlMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // 先让后续中间件处理请求(包括认证逻辑) await _next(context); // 检查是否是重定向响应(301/302) if (context.Response.StatusCode is StatusCodes.Status301MovedPermanently or StatusCodes.Status302Found) { var location = context.Response.Headers.Location.ToString(); if (!string.IsNullOrEmpty(location)) { // 解析URL并移除ReturnUrl参数 var uri = new Uri(location); var queryParams = HttpUtility.ParseQueryString(uri.Query); queryParams.Remove("ReturnUrl"); // 重新构建跳转URL var newLocationBuilder = new UriBuilder(uri) { Query = queryParams.Count > 0 ? queryParams.ToString() : string.Empty }; // 更新响应的Location头 context.Response.Headers.Location = newLocationBuilder.Uri.ToString(); } } } } // 扩展方法,方便在Startup里注册 public static class RemoveReturnUrlMiddlewareExtensions { public static IApplicationBuilder UseRemoveReturnUrl(this IApplicationBuilder app) { return app.UseMiddleware<RemoveReturnUrlMiddleware>(); } }
注册中间件
在Configure方法里,把这个中间件注册在认证中间件之前(因为响应是反向流转的,这样才能拦截到认证中间件发出的重定向):
app.UseRemoveReturnUrl(); app.UseAuthentication(); app.UseAuthorization();
这样,所有重定向响应里的ReturnUrl参数都会被自动移除。
内容的提问来源于stack exchange,提问作者Bob Meijwaard
相关产品推荐
相关产品推荐

