首页 > 解决方案 > .NETCore 中间件重定向删除路径 IIS 子应用程序

问题描述

我有一个中间件类,它读取用户的 cookie 并验证它们,如果它们无效或丢失,则重定向到登录 URL。用户被重定向到的 URL 包含一个“返回”参数。当应用程序不是 IIS 中的嵌套应用程序时,此中间件在静态文件 SPA 上运行良好。

我的问题,这在使用 MVC 控制器和视图时不起作用,在用户以某种方式重定向到登录页面之前,路径(指向嵌套的 IIS 站点)被剥离并且后 URL 不包含 URL 路径。有任何想法吗?

怎么了

转到-> http://test.com/mysite

重定向到 -> http://login.com?back= http://test.com

应该发生什么

转到-> http://test.com/mysite

重定向到 -> 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);
      }
    }

  }

}

标签: asp.net-mvciisasp.net-coreroutingmiddleware

解决方案


这可能是 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)}");

推荐阅读