c# - 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);
解决方案
以“/”开头的重定向 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 路径以命名项目(例如目录或页面,如“身份”)开头,以相对于当前路径引用它。如果页面只能从单个目录/页面访问(或者,不太可能,您有一个确保路径始终存在的命名约定),请使用此选项。
推荐阅读
- ios - Swift Playgrounds 书架标题
- javascript - 克隆适用于所有点击的元素,而不是这个
- php - Yii2 - 返回空 API 响应
- charts - Flutter Google Chart Gauge - 将标签放置在中心
- php - WordPress 网站上可恢复的致命错误
- node.js - 如何使用 ES6 标准启动服务器
- objective-c - 如何修复目标 c 中的内存泄漏?
- javascript - 在 html5 选择中获取所选选项的键(文本)
- elasticsearch - 应用洞察与弹性(ELK)
- angular - 错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“侦听器”-离子3