ASP.NET Core Razor页面未执行错误模型的获取 [英] ASP.NET Core Razor Pages OnGet of Error model not being executed

查看:14
本文介绍了ASP.NET Core Razor页面未执行错误模型的获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我修改了默认的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>

以下是我在Startup类中的配置方法以供参考

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是空的。我在OnGet方法中设置了断点,并确认它没有被执行。

我还尝试使用中间件记录我的异常,但也不起作用。

有人知道这可能是什么原因吗?

推荐答案

有两个原因导致app.UseExceptionHandler("/Error")因许多错误而停止工作。

  1. ExceptionHandler可以通过GET方法或POST方法调用Error页,POST方法将在POST向服务器请求并发生异常时调用。

  2. 当从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>();
        ....
    }
}

享受吧!

这篇关于ASP.NET Core Razor页面未执行错误模型的获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆