我的API有很多db调用,因此我需要使用FirstorDefault
或FirstorDefaultAsync
处理几乎每个数据库调用,但是有没有比这更好的方法
if (user == null) return NotFound();
每次我要从数据库中检索用户行时?
我最终使用了IAsyncActionFilter
,我的代码:
public class SampleAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var result = await next();
if (result.Exception == null || result.Exception.GetType() != typeof(InvalidOperationException)) return;
result.Result = new NotFoundObjectResult("Row was not found");
result.ExceptionHandled = true;
}
}
和configureReservices
函数
services.AddMvc(f => f.Filters.Add(new SampleAsyncActionFilter()));