Home > Software engineering >  get Original URL (after redirect to 404 page) in Error Controller
get Original URL (after redirect to 404 page) in Error Controller

Time:05-04

I want to get the original path (entered by the user) in the error controller after redirect to the 404 error page ?!

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

and in Error Controller

return View("ErrorPage", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,
RequestedUrl = "", RedirectUrl = HttpContext.Request.GetDisplayUrl(), ExceptionMessage = ReasonPhrases.GetReasonPhrase(statusCode) });

enter image description here

CodePudding user response:

UPDATE:

You also can refer below method.

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 >@ViewData["statusCode"]</h1>
<h2 >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>

Test Result:

enter image description here


PREVIOUS:

If you want get request url and redirect url, I suggest you can use RedirectToAction method.

Please check below page, if it is you want pls let me know.

enter image description here

And in my test code, I also use middleware to handle 302 event.

  • Related