asp.net-mvc - .NETCore 中间件重定向删除路径 IIS 子应用程序
问题描述
我有一个中间件类,它读取用户的 cookie 并验证它们,如果它们无效或丢失,则重定向到登录 URL。用户被重定向到的 URL 包含一个“返回”参数。当应用程序不是 IIS 中的嵌套应用程序时,此中间件在静态文件 SPA 上运行良好。
我的问题,这在使用 MVC 控制器和视图时不起作用,在用户以某种方式重定向到登录页面之前,路径(指向嵌套的 IIS 站点)被剥离并且后 URL 不包含 URL 路径。有任何想法吗?
怎么了
重定向到 -> http://login.com?back= http://test.com
应该发生什么
重定向到 -> http://login.com?back= http://test.com/mysite
public class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly IOptions<MyMiddlewareOptions> _options;
public MyMiddleware(RequestDelegate next, IOptions<MyMiddlewareOptions> options, ILoggerFactory logger)
{
_next = next;
_options = options;
_logger = logger.CreateLogger("My Middleware");
}
public async Task Invoke(HttpContext context)
{
var middlewareCookieValidator = context.RequestServices.GetService<IMiddlewareCookieValidator>();
await new CookieRequestCultureProvider().DetermineProviderCultureResult(context);
if (!_options.Value.Bypass && !Path.HasExtension(context.Request.Path.Value))
{
try
{
if (wslCookieValidator.HasCreatedCookies(context) || await middlewareCookieValidator.ValidateCookiesAsync())
{
context.Response.OnStarting(async () => await middlewareCookieValidator.GenerateAndApplyCookiesToResponse(context));
await _next(context);
}
else
{
var location = new Uri($"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}");
context.Response.Redirect($"{_options.Value.Url}?back={location}");
}
}
catch (Exception exception)
{
throw new Exception($"RequestDelegate '_next' = {_next}. {exception.Message}");
}
}
else
{
await _next(context);
}
}
}
}
解决方案
这可能是 URL 编码问题。您应该使用 对传入back
查询字符串参数的 URL 进行编码System.Net.WebUtility.UrlEncode()
。例如:
using System.Net;
// ...
var location = new Uri($"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}");
context.Response.Redirect($"{_options.Value.Url}?back={WebUtility.UrlEncode(location)}");
推荐阅读
- postgresql - 在 Ubuntu 20.04 中运行 postgresql 的命令是什么
- python - Django 模型子类的类型提示
- c# - 将 Azure 应用服务与本地托管的 IIS WCF 服务通信
- jquery - 如何在 jQuery ajax 的用户代理中添加附加信息?
- angular - 如何从 Ionic Capacitor 打开的 javascript 关闭窗口
- python - Python PDF to TXT 本地字符
- sprite - 获取鼠标输入时如何在glfw中绘制光标?
- python - Python Prefect 上的 MySQL 连接
- javascript - 在选择多个复选框时将属性附加到变量
- html - 如何设置动态div高度