c# - ASP.Net Core异常处理中间件

标签 c# asp.net-core asp.net-core-webapi asp.net-core-middleware

我正在尝试将中间件用于ASP.Net Core 3.0 Web API项目中的异常处理:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleException(context, ex);
        }
    }

    private static Task HandleException(HttpContext context, Exception ex)
    {
        HttpStatusCode code = HttpStatusCode.InternalServerError; // 500 if unexpected

        // Specify different custom exceptions here
        if (ex is CustomException) code = HttpStatusCode.BadRequest;

        string result = JsonConvert.SerializeObject(new { error = ex.Message });

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;

        return context.Response.WriteAsync(result);
    }
}

startup.cs
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add controllers with a route prefix
        services.AddControllers(x => { x.UseGeneralRoutePrefix($"api/v{Configuration["APIVersion"]}"); });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v0.1", new OpenApiInfo { Title = "My API", Version = "v0.1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v0.1/swagger.json", "My API V1");
        });

        app.UseMiddleware(typeof(ErrorHandlingMiddleware));

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Controller
[HttpPost]
public ActionResult Method()
{
    if (condition)
        throw new CustomException();
    else
        return Ok();
}

但是 Controller 中抛出的异常不会被中间件处理。使用中间件的正确方法是什么?

最佳答案

看起来

app.UseDeveloperExceptionPage();

阻止了异常处理中间件捕获异常。删除它可以解决问题。

关于c# - ASP.Net Core异常处理中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821308/

相关文章:

c# - 级联下拉 MVC3 返回空下拉字段

c# - Json.NET 无法序列化集合字典

c# - 使用 C# 将文档发送到打印机

angular - 使用基本 href 从不同的子目录提供 angular2

angular - 如何从 Angular(或另一个 SPA)对 Asp.Net Core Identity 进行身份验证?

c# - Visual Studio 在开发模式下崩溃

docker - .Net Core 不能使用支持 Docker 的 Add-migrations

c# - ASP.NET Core 处理方法不允许 405

c# - 在从 C# Web api 生成的 swagger 中包含格式

performance-testing - dotnet core WebAPI的性能测试