Witam mam problem z własnym middleware w asp.net. Uczyłem się z kanału Fullstack Developer, który wystąpił na kanale Pasja Informatyki. Kod jest 1:1 jak na filmiku, ale blok try catch nie wychwytuje błędu. Sprawdzałem przez narzędzie debugowania i wszystko ładnie przechodzi przez middleware ale błędu nie łapie.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace ASP3.Middleware
{
public class ErrorHandlingMiddleware : IMiddleware
{
private readonly ILogger<ErrorHandlingMiddleware> _logger;
public ErrorHandlingMiddleware(ILogger<ErrorHandlingMiddleware> logger)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
context.Response.StatusCode = 500;
await context.Response.WriteAsync("Something went wrong!");
}
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<RestaurantDbContext>();
services.AddScoped<RestaurantSeeder>();
services.AddAutoMapper(this.GetType().Assembly);
services.AddScoped<IRestaurantService, RestaurantService>();
services.AddScoped<ErrorHandlingMiddleware>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RestaurantSeeder seeder)
{
seeder.Seed();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
