Reputation: 1126
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
}
}
Upvotes: 2
Views: 1519
Reputation: 27997
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:
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;
}
Upvotes: 5