c# - web api 2 ExceptionHandlerFilter OnExceptionAsync 未触发

标签 c# asynchronous asp.net-web-api error-handling async-await

经过 6 年的开发,这是我的第一个问题,所以...大家好。 我到处都搜索过这个主题,但没有任何帮助。

我已将所有 Controller 的方法从同步移动到异步。在一切正常之前,当抛出异常时,会触发 OnException 方法。

现在,当在异步 Controller 方法中抛出异常时,无法触发 OnException 或 OnExceptionAsync 方法。

这是我的代码

  public class ExceptionHandlerFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        var resp = new HttpResponseMessage();
        resp.Content = new StringContent(context.Exception.Message + Environment.NewLine + Environment.NewLine + context.Exception.StackTrace);

        if (context.Exception is NotImplementedException)
            resp.StatusCode = HttpStatusCode.NotImplemented;
        else if (context.Exception is NotFoundException)
            resp.StatusCode = HttpStatusCode.NotFound;
        else if (context.Exception is ArgumentException)
            resp.StatusCode = HttpStatusCode.BadRequest;
        else
            resp.StatusCode = HttpStatusCode.InternalServerError;

        context.Response = resp;
    }

    public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
    {
        var task = base.OnExceptionAsync(context, cancellationToken);
        return task.ContinueWith((t) =>
        {
            var resp = new HttpResponseMessage();
            resp.Content = new StringContent(context.Exception.Message + Environment.NewLine + Environment.NewLine + context.Exception.StackTrace);

            if (context.Exception is NotImplementedException)
                resp.StatusCode = HttpStatusCode.NotImplemented;
            else if (context.Exception is NotFoundException)
                resp.StatusCode = HttpStatusCode.NotFound;
            else if (context.Exception is ArgumentException)
                resp.StatusCode = HttpStatusCode.BadRequest;
            else
                resp.StatusCode = HttpStatusCode.InternalServerError;

            context.Response = resp;
        });
    }        
}

这是我的 Controller

[ExceptionHandlerFilter]
public class FascicolazioneController : ApiController
{      

    [ActionName("ClassificaFascicolaArchivisticamente")]
    [HttpPost]
    public async void ClassificaFascicolaArchivisticamente(string progressivoAnnuo, string archivio, int fascicoloId, string classificazione)
    {
        try
        {
            throw new NotImplementedException();
        }
        catch (Exception ex)
        {
            throw ex;
        }

        using (var client = new Cad.BDI.Archiflow.FacadeArchiflow("SUPER", this.GetTypeAndMethodName()))
        {


            await Task.Factory.StartNew(() => client.ClassificaFascicolaArchivisticamente(
                ProgressivoAnnuo.Parse(progressivoAnnuo), archivio, fascicoloId, Classificazione.Parse(classificazione)));
        }
    }

我尝试在 WebApiConfig 和/或 global.asax 中设置正确的代码行,添加 ExceptionHadlerFilter 除了仅在 Controller 上设置属性外,但没有任何帮助

最佳答案

这篇文章让我明白了

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396

问题是 Controller 方法的签名。从不使用

    public async void Bla(){}

我应该用

   public async Task Bla(){}

关于c# - web api 2 ExceptionHandlerFilter OnExceptionAsync 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674283/

相关文章:

c# - 如何从 Expression<Func<MyClass, string>> 动态创建 Expression<Func<MyClass, bool>> 谓词?

使用 Wallpaper Manager 的 Android AsyncTask

django - 如何在 Django View 中最好地启动异步作业请求?

c# - 等待 Task.Factory.FromAsync(BeginXxx, EndXxx) 后 HttpContext 为空

asp.net - ASP 5 MVC 6 - 优点和缺点 : multiple web api services - use one or more projects?

c# - 数学库中 Math.tanh 的倒数在哪里?

c# - 将对象转换为集合

c# - 查询SQL时DateTime转换错误

c# - 作为 json 返回时排除某些字段

c# - 结果类型未知的任务