提问人:ghasem deh 提问时间:5/3/2022 更新时间:5/3/2022 访问量:665
在错误控制器中获取原始 URL(重定向到 404 页面后)
get Original URL (after redirect to 404 page) in Error Controller
问:
我想在重定向到 404 错误页面后在错误控制器中获取原始路径(由用户输入)?!
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public string RequestedUrl { get; set; }
public string RedirectUrl { get; set; }
public string ExceptionMessage { get; set; }
}
和错误控制器
return View("ErrorPage", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,
RequestedUrl = "", RedirectUrl = HttpContext.Request.GetDisplayUrl(), ExceptionMessage = ReasonPhrases.GetReasonPhrase(statusCode) });
答:
3赞
Jason Pan
5/3/2022
#1
更新:
您也可以参考以下方法。
启动.cs:
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
ErrorViewModel.cs:
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public string RequestedUrl { get; set; }
public string RedirectUrl { get; set; }
public string ExceptionMessage { get; set; }
}
首页控制器 .cs:
public IActionResult Error()
{
var statusCode = HttpContext.Response.StatusCode;
ViewData["statusCode"] = statusCode;
var feauter = Request.HttpContext.Features.Get<IStatusCodeReExecuteFeature>();//=null
var path = feauter?.OriginalPath;
return View("ErrorPage", new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,
RequestedUrl = path,
RedirectUrl = HttpContext.Request.GetDisplayUrl(),
ExceptionMessage = ReasonPhrases.GetReasonPhrase(statusCode)
});
}
ErrorPage.cshtml:
@model ErrorViewModel
@{
ViewData["Title"] = "ErrorPage";
}
<h1 class="text-danger">@ViewData["statusCode"]</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<div>RequestId :@Model.RequestId</div>
<div>ShowRequestId :@Model.ShowRequestId</div>
<div>RequestedUrl :@Model.RequestedUrl</div>
<div>RedirectUrl :@Model.RedirectUrl</div>
<div>ExceptionMessage:@Model.ExceptionMessage</div>
测试结果:
以前:
如果你想要获取请求网址和重定向网址,我建议你可以使用方法。RedirectToAction
请查看以下页面,如果您想要,请告诉我。
在我的测试代码中,我还使用中间件来处理 302 事件。
评论