ExceptionFilter无法运行.NET Core Web Api

问题描述 投票:0回答:1

我对动作过滤器有疑问。我的过滤器均未运行。我正在使用.NET Core 2.2并构建Web Api。我在控制器中的[CustomExceptionFilter]中注册了它:

[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);
}

有什么问题?

c# .net .net-core action-filter custom-action-filter
1个回答
0
投票

我不确定您的示例出了什么问题,但这就是我的做法。

首先是异常过滤器:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {

然后我将过滤器添加到整个控制器,而不仅仅是一个动作,尽管这可能也可以工作-我从未尝试过:

[ServiceFilter(typeof(CustomExceptionFilterAttribute))]
public class MyController : ControllerBase
{

并且在Startup.cs中,ConfigureServices,添加DI支持:

services.AddScoped<CustomExceptionFilterAttribute>();

blog会更详细。

© www.soinside.com 2019 - 2024. All rights reserved.