我正在尝试创建一个异常处理中间件,但是它无法按我需要的方式工作。我需要获取可以从系统任何点抛出的异常,然后中间件将获取异常,然后将异常消息和http代码返回给客户端作为响应。当我调试时,断点到达中间件,并且我可以看到异常消息,但是该消息和代码没有返回给客户端。
这是代码:
public class ErrorDto
{
public int StatusCode { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
app.UseCors("Dev");
else
app.UseHsts();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorDto()
{
StatusCode = context.Response.StatusCode,
Message = ex.Message
}.ToString(), Encoding.UTF8);
}
});
});
app.UseMvc(opts =>
{
opts.MapRoute(
name: "default",
template: "api/{controller}/{action}/{id?}");
});
}