ASP.NET Core Razor Pages Модель OnGet of Error не выполняется - PullRequest
0 голосов
/ 30 сентября 2019

Я изменил значение по умолчанию Error.cshtml.cs, чтобы оно регистрировалось при возникновении ошибки, и она работала некоторое время. Теперь после обновления до .NET Core 3.0 он больше не работает.

Вот моя 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();
    }
}

А вот моя ошибка 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>

Для справки вот мой метод Configure в моем классе запуска

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

Проблема в том, что my ShowRequestId всегда ложно, то есть my RequestId равно нулю или пусто. Я установил точку останова в своем методе OnGet и подтвердил, что он не выполняется.

Я также пытался использовать Middelware для регистрации моих исключений, но это тоже не сработало.

У кого-нибудь есть идеячто может быть причиной этого?

1 Ответ

0 голосов
/ 01 октября 2019

Вы можете попробовать использовать промежуточное ПО, как показано ниже:

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, вы можете вызвать метод UseStatusCodePages перед обработкой запросапромежуточное ПО (например, промежуточное ПО статических файлов и промежуточное ПО MVC) в Configuremethod класса запуска.

Ссылка:

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

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

...