C# .net核心API和网页控制器的不同错误处理
我正在尝试在一个新的.NETCore2.2Web应用程序项目中设置异常处理 目前,我尝试了两种方法——生存C# .net核心API和网页控制器的不同错误处理,c#,asp.net-core,asp.net-core-mvc,asp.net-core-webapi,C#,Asp.net Core,Asp.net Core Mvc,Asp.net Core Webapi,我正在尝试在一个新的.NETCore2.2Web应用程序项目中设置异常处理 目前,我尝试了两种方法——生存 使用内置的异常处理程序:app.UseExceptionHandler,app.UseStatusCodePages,等等 创建了我自己的中间件来处理异常,我已将其添加到问题的底部 现在,主要的问题是我可以使用自己的自定义中间件,但是(当然)这在所有请求上都会使用,而不仅仅是在API调用上 我想要实现的是将Web API和Web页面的异常逻辑分开,这样我就可以使用自定义中间件和API的返回
app.UseExceptionHandler
,app.UseStatusCodePages
,等等app.UseDeveloperExceptionPage()
例如用于Web页面
例外中间件供参考:
公共静态类ExceptionMiddleware
{
public static void ConfigureExceptionHandler(此IAApplicationBuilder应用程序,ILoggerFactory,
bool includeStackTrace=false)
{
app.UseExceptionHandler(生成器=>
运行(异步上下文=>
{
var logger=loggerFactory.CreateLogger(name of(ExceptionMiddleware));
//设置响应状态代码
context.Response.StatusCode=(int)HttpStatusCode.InternalServerError;
context.Response.ContentType=“应用程序/json”;
var contextFeature=context.Features.Get();
if(contextFeature!=null)
{
//获取当前异常
var currentException=contextFeature.Error;
LogError(currentException,$“出现了错误:{currentException}”);
错误详细信息错误详细信息;
如果(包括堆栈跟踪)
errorDetails=新扩展的errorDetails
{
StatusCode=(HttpStatusCode)context.Response.StatusCode,
Message=currentException.Message,
StackTrace=currentException.StackTrace
};
其他的
errorDetails=新的errorDetails
{
StatusCode=(HttpStatusCode)context.Response.StatusCode,
Message=“内部服务器错误。”
};
//写下回应
wait context.Response.WriteAsync(JsonConvert.SerializeObject(errorDetails));
}
}));
}
私有类错误详细信息
{
公共HttpStatusCode状态码{[UseDimplicity]get;set;}
公共字符串消息{[UseDimplicity]get;set;}
}
私有类ExtendedErrorDetails:ErrorDetails
{
公共字符串StackTrace{[UseDimplicity]get;set;}
}
}
您无法从异常中识别错误,我建议您尝试为mvc和web api制定不同的路径。对于web api,使用api
添加属性route,然后在中间件或异常处理程序中检查请求路径,如
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>() as ExceptionHandlerFeature;
var requestPath = error.Path;
});
});
我尝试使用context.Request.GetEncodedUrl()检查路径,但我不知道当它不是API调用时如何使用
UseDeveloperCeptionPage
。@n即使您可以使用UseWhen
配置API的ExceptionHandler。检查更新。
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>() as ExceptionHandlerFeature;
var requestPath = error.Path;
});
});
app.UseDeveloperExceptionPage();
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), subApp =>
{
subApp.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await context.Response.WriteAsync("Error");
});
});
});