IIS 上托管的 Asp.Net 核心中间件响应重定向 URL 不完整

时间:2021-02-08 21:03:50

标签: c# asp.net asp.net-core iis

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

预期网址:myDomain/文件夹/Identity/Account/ChangePassword

实际网址: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);

1 个答案:

答案 0 :(得分:0)

以“/”开头的重定向 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 到 razor 页面(即 string location = "/Folder/Identity/Account/ChangePassword";。这将始终从任何地方重定向到 /Folder/Identity/Account/ChangePassword在应用程序中。

总结:

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