【发布时间】:2020-06-17 23:16:40
【问题描述】:
我有一个像这样的自定义中间件设置。
using AutoWrapper.Wrappers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace BBBankApi
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
if (context.Response.HasStarted)
{
throw;
}
_logger.LogError(new EventId(), ex, ex.Message);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var json = JsonConvert.SerializeObject(new ApiException(ex));
await context.Response.WriteAsync(json);
}
}
}
public static class CustomExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptiontusMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExceptionMiddleware>();
}
}
}
在启动时是这样配置的
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCustomExceptiontusMiddleware(); //<-- *******Right Here
app.UseApiResponseAndExceptionWrapper();
app.UseCors(MyAllowSpecificOrigins);
app.UseMvc(b =>
{
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
当我提出请求时,我确实点击了 await _next.Invoke(context);行,但我在代码中提出了一个新的异常(“出错了”)。但是在中间件的 catch 块中没有收到这个异常。
我正在使用来自 https://vmsdurano.com/autowrapper-prettify-your-asp-net-core-apis-with-meaningful-responses/ 的 AutoWrapper 但我不认为它在这里有很大的不同。
【问题讨论】: