在错误控制器中获取原始 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) });

更新:

你也可以参考下面的方法

Startup.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; }
}

HomeController.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>

测试结果:


上一个:

如果你想获取请求url并重定向url,我建议你可以使用RedirectToAction方法。

请查看下面的页面,如果你想要请告诉我。

并且在我的测试代码中,我也使用了中间件来处理302事件。