简体   繁体   English

ASP.NET 内核 Razor 页面 OnGet 错误 model 未执行

[英]ASP.NET Core Razor Pages OnGet of Error model not being executed

I modified the default Error.cshtml.cs to log when an error gets thrown, and it worked for a while.我修改了默认的Error.cshtml.cs以在抛出错误时进行记录,并且它工作了一段时间。 Now after updating to .NET Core 3.0 release it's no longer working.现在更新到 .NET Core 3.0 版本后,它不再工作了。

Here is my ErrorModel:这是我的错误模型:

[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();
    }
}

And here is my Error cshtml:这是我的错误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>

For reference here is my Configure Method in my Startup class供参考的是我的启动 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();
}

The problem is that my ShowRequestId is always false, meaning my RequestId is null or empty.问题是我的ShowRequestId总是假的,这意味着我的RequestId是 null 或空。 I put a breakpoint in my OnGet method and confirmed it's not being executed.我在 OnGet 方法中设置了一个断点并确认它没有被执行。

I also tried using a Middelware to log my Exceptions, but that didn't work either.我还尝试使用 Middelware 来记录我的异常,但这也不起作用。

Anybody have an idea what could be causing this?有人知道是什么原因造成的吗?

I think your error is produced in a POST, PUT or DELETE, and you are trying to controlate it in the OnGet method of ErrorModel, this is executed only for errors produced in GET operations我认为您的错误是在 POST、PUT 或 DELETE 中产生的,并且您试图在 ErrorModel 的 OnGet 方法中控制它,这仅针对 GET 操作中产生的错误执行

Hope this helps!!!希望这可以帮助!!!

There are 2 reasons that app.UseExceptionHandler("/Error") stopped working for many of errors. app.UseExceptionHandler("/Error")因许多错误而停止工作有两个原因。

  1. ExceptionHandler could invoke Error page either by GET method or POST method, POST method will be called when you POST a request to server and exception occurred. ExceptionHandler 可以通过GET方法或POST方法调用Error页面,当您向服务器POST请求并发生异常时,将调用POST方法。

  2. When POST method is invoked from ExceptionHandler, it can't reach the Error page if you don't add the [IgnoreAntiforgeryToken] to PageModel .从 ExceptionHandler 调用POST方法时,如果不将[IgnoreAntiforgeryToken]添加到PageModel ,则无法到达Error页面。

So you have to add OnPost method and attribute [IgnoreAntiforgeryToken] .所以你必须添加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>();
        ....
    }
}

Enjoy it!好好享受!

You could try to use middleware like below:您可以尝试使用如下中间件:

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

If you want to show the error pages of the HTTP Status codes, you could call the UseStatusCodePages method before request handling middleware (for example, Static File Middleware and MVC Middleware) in the Configuremethod of the Startup class.如果要显示 HTTP 状态码的错误页面,可以在 Startup ZA2CDZ2ED4F8EBC2CBB1 的 Configuremethod 中的请求处理中间件(例如 Static 文件中间件和 MVC 中间件)之前调用UseStatusCodePages方法。

Reference:参考:

https://www.learnrazorpages.com/configuration/custom-errors https://www.learnrazorpages.com/configuration/custom-errors

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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