简体   繁体   中英

Asp.net core: How to get original path in error page by 404 status code

In my asp.net core application, after each error that occurs, the requested address is changed to the site error page address How can I retrieve the original requested address in the error page?
Startup.cs:

public class Startup
{
    private const string ErrorHandlingPath = "/Error";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseExceptionHandler(ErrorHandlingPath);

        app.UseStatusCodePagesWithReExecute(ErrorHandlingPath);;

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

Error.cshtml.cs


    public class ErrorModel : PageModel
    {
        public void OnGet()
        {
            var status = HttpContext.Response.StatusCode;//=404
            var originalPath = HttpContext.Request.Path.Value;//=Error
            var feauter = Request.HttpContext.Features.Get<IExceptionHandlerPathFeature>();//=null
            var path = feauter?.Path;//=null
        }
    }

As far as I know, you could get the orginal path by using below codes:

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()    
    {
        //var re = HttpContext.Request.Path;
        var feauter = Request.HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        var path = feauter.Path;

        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

Result:

在此处输入图像描述

Update

Since you used razor page's statuscode re-execute method, you should use IStatusCodeReExecuteFeature.

More details, you could refer to below codes:

    public void OnGet()
    {

        var feauter = Request.HttpContext.Features.Get<IStatusCodeReExecuteFeature>();//=null
        var path = feauter?.OriginalPath;//=null
        RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
    }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM