首页 > 解决方案 > IIS 上托管的 Asp.Net Core 中间件响应重定向 URL 不完整

问题描述

我有一个托管在 IIS 上的应用程序。我正在使用中间件来检测登录用户是否必须在管理员重置密码后更改密码。当我尝试将响应重定向到剃刀页面以更改密码时,由于缺少虚拟目录路径,重定向似乎不完整。这导致一个Server Error 404 - File or directory not found.

预期 URL:myDomain/ FOLDER /Identity/Account/ChangePassword

实际 URL:myDomain/Identity/Account/ChangePassword

我的中间件重定向部分如下所示:

    var returnUrl = context.Request.Path.Value == "/" ? string.Empty : "?returnUrl=" + HttpUtility.UrlEncode(context.Request.Path.Value);
        
    string location= "/Identity/Account/ChangePassword";
    context.Response.Redirect(location + returnUrl);
    await _next(context);

标签: c#asp.netasp.net-coreiis

解决方案


以“/”开头的重定向 URL 将始终适用于您的域,例如

// Current URL: https://localhost:5001/Folder/Page
context.Response.Redirect("/Page2"); // navigates to: https://localhost:5001/Page2

// vs.

context.Response.Redirect("Page2"); // navigates to: https://localhost:5001/Folder/Page2

如果您希望该位置相对于当前目录,请删除初始正斜杠:

var returnUrl = context.Request.Path.Value == "/" 
    ? string.Empty 
    : "?returnUrl=" + HttpUtility.UrlEncode(context.Request.Path.Value);
        
string location = "Identity/Account/ChangePassword"; // <- change here
context.Response.Redirect(location + returnUrl);
await _next(context);

更新

关于您的评论,您可能希望使用剃须刀页面的绝对 URI(即string location = "/Folder/Identity/Account/ChangePassword";。这将始终从应用程序中的任何位置重定向到/Folder/Identity/Account/ChangePassword

总之:

  • URI 路径以“/”开头,以将其范围限定为根(即域)。从应用程序中的任何位置引用路径时使用此选项。
  • URI 路径以命名项目(例如目录或页面,如“身份”)开头,以相对于当前路径引用它。如果页面只能从单个目录/页面访问(或者,不太可能,您有一个确保路径始终存在的命名约定),请使用此选项。

推荐阅读