My API has a lot of db calls so I need to handle practically every database call with FirstOrDefault
or FirstOrDefaultAsync
, but is there a way to do it better then
if (user == null) return NotFound();
every time I want to retrieve User row from database?
I ended up using IAsyncActionFilter
, my code:
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;
}
}
And ConfigureServices
function
services.AddMvc(f => f.Filters.Add(new SampleAsyncActionFilter()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.