ExceptionFilter 不运行 .NET Core Web Api [英] ExceptionFilter doesn't run .NET Core Web Api
本文介绍了ExceptionFilter 不运行 .NET Core Web Api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有操作过滤器的问题.我的过滤器都没有运行.我正在使用 .NET Core 2.2 并构建 Web Api.我在控制器中用 [CustomExceptionFilter] 注册了它:
I have problem with Action Filters. None of my filters run. I am using .NET Core 2.2 and building Web Api. I registered it with [CustomExceptionFilter] in controller:
[HttpDelete("{id}")]
[CustomExceptionFilter]
public IActionResult Delete(int id)
{
var piano = _repository.GetPianoById(id);
if (piano == null) throw new Exception();
_repository.Delete(id);
return Ok();
}
这是我的异常过滤器:
using System.Web.Http.Filters;
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = actionExecutedContext.Exception.GetType();
if (exceptionType == typeof(Exception))
{
message = "Incorrect ID.";
status = HttpStatusCode.NotFound;
}
actionExecutedContext.Response = new HttpResponseMessage()
{
Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"),
StatusCode = status
};
base.OnException(actionExecutedContext);
}
有什么问题?
推荐答案
我不确定你的例子有什么问题,但我就是这样做的.
I am not sure what is wrong with your example, but this is how I have done it.
首先是异常过滤器:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
然后我将过滤器添加到整个控制器,而不仅仅是一个动作,尽管这也可能有效——我从未尝试过:
I then add the filter to the whole controller, not just an action, although that might work too--I have never tried it:
[ServiceFilter(typeof(CustomExceptionFilterAttribute))]
public class MyController : ControllerBase
{
并在 Startup.cs、ConfigureServices 中添加 DI 支持:
And in Startup.cs, ConfigureServices, add DI support:
services.AddScoped<CustomExceptionFilterAttribute>();
这个 博客 更详细.
这篇关于ExceptionFilter 不运行 .NET Core Web Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文