经过 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/