[英]ASP.NET Core Razor Pages OnGet of Error model not being executed
我修改了默認的Error.cshtml.cs
以在拋出錯誤時進行記錄,並且它工作了一段時間。 現在更新到 .NET Core 3.0 版本后,它不再工作了。
這是我的錯誤模型:
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public IActionResult OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
try
{
Logger.LogMessage(new LogMessage
{
RequestId = RequestId,
Exception = exceptionHandlerPathFeature?.Error,
Time = DateTime.Now
});
}
catch (Exception)
{
// ignored
}
return Page();
}
}
這是我的錯誤cshtml:
@page "/Error"
@model ErrorModel
@{
ViewData["Title"] = "Error";
}
<h2 class="text-danger">Ein Fehler ist aufgetreten.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Anfrage ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Hoppla, das sollte nicht passieren</h3>
<p>
Bitte merken Sie sich doch den Ablauf der zu diesem Fehler führte und melden Sie ihn dem
verantwortlichen Entwickler somit er behoben werden kann. Bitte fügen Sie auch mindestens die ersten 8 Zeichen der Anfrage ID an
</p>
供參考的是我的啟動 class 中的配置方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseSession();
if (env.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<FingerprintHub>("/Hub/FingerprintHub");
endpoints.MapHub<RegistrationHub>("/Hub/RegistrationHub");
});
app.UseWebSockets();
}
問題是我的ShowRequestId
總是假的,這意味着我的RequestId
是 null 或空。 我在 OnGet 方法中設置了一個斷點並確認它沒有被執行。
我還嘗試使用 Middelware 來記錄我的異常,但這也不起作用。
有人知道是什么原因造成的嗎?
我認為您的錯誤是在 POST、PUT 或 DELETE 中產生的,並且您試圖在 ErrorModel 的 OnGet 方法中控制它,這僅針對 GET 操作中產生的錯誤執行
希望這可以幫助!!!
app.UseExceptionHandler("/Error")
因許多錯誤而停止工作有兩個原因。
ExceptionHandler 可以通過GET
方法或POST
方法調用Error
頁面,當您向服務器POST
請求並發生異常時,將調用POST
方法。
從 ExceptionHandler 調用POST
方法時,如果不將[IgnoreAntiforgeryToken]
添加到PageModel
,則無法到達Error
頁面。
所以你必須添加OnPost
方法和屬性[IgnoreAntiforgeryToken]
。
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
...
public ActionResult OnGet()
{
HandleError();
return Page();
}
public ActionResult OnPost()
{
HandleError();
return Page();
}
private void HandleError()
{
...
var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
....
}
}
好好享受!
您可以嘗試使用如下中間件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//else
//{
// app.UseExceptionHandler("/Error");
// // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// app.UseHsts();
//}
app.Use(async (Context, next) =>
{
try
{
await next();
}
catch (Exception e)
{
Context.Response.Redirect("/Error");
}
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
如果要顯示 HTTP 狀態碼的錯誤頁面,可以在 Startup ZA2CDZ2ED4F8EBC2CBB1 的 Configuremethod 中的請求處理中間件(例如 Static 文件中間件和 MVC 中間件)之前調用UseStatusCodePages方法。
參考:
https://www.learnrazorpages.com/configuration/custom-errors
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.