我有ASP。NETCORE 3.1 WEBAPI,Azure SQL server作为应用程序的数据库。
为了避免重复的代码,我考虑实现一个过滤器,该过滤器将根据API端点返回的结果来决定HTTP状态代码。这里的想法是删除与设置相关的重复代码,结果总是与HTTP状态代码一起返回。
我想知道的是,在执行操作方法后,放弃将响应与结果和适当的HTTP状态代码一起发送回客户端的传统方法,还是将其委托给操作过滤器,这是一种好的做法。
代码(不带筛选器):
[HttpGet("{param1:long}", Name = "GetData")]
[ResponseCache(CacheProfileName = "Never")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<TestModel>> GetData(long param1)
{
var result = await _testService.GetData(param1);
return result is null ? NotFound() : (ActionResult<TestModel>)Ok(result);
}
代码(带筛选器)
[HttpGet("{param1:long}", Name = "GetData")]
[ResponseCache(CacheProfileName = "Never")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
[ServiceFilter(typeof(StatusFilter))]
public async Task<ActionResult<TestModel>> GetData(long param1)=>
await _testService.GetData(param1);
// Filter to handle the HTTP Status code
public class StatusFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var value = ((Microsoft.AspNetCore.Mvc.ObjectResult)context.Result).Value;
if (value is null)
{
context.Result = new NotFoundResult(value);
}
else
{
context.Result = new OkObjectResult(value);
}
}
}
有没有更好的方法来实施它。
有人能在这里为我提供指导吗?