在我的大多数控制器(API)(.net core 3.1)中,我调用一个函数并使用该函数的响应来创建适当的操作结果。看起来像这样:
[HttpPost("{id}/read")]
public async Task<IActionResult> ReadMessage(Guid id)
{
ResponseApiModel r = await _messageData.ReadOneMessage(id);
if (r.ApiResponse != ApiResponse.AllGood)
{
if (r.ApiResponse == ApiResponse.NotFound)
return NotFound(r);
else
return BadRequest(r);
}
}
事实是,在整个控制器上的多个动作中,基本上都会重复执行if语句。我希望能够将此代码移至“动作过滤器”。但是无法弄清楚该怎么做。毕竟我该如何将ResponeApiModel传递给过滤器。
我已经将所有其他通用代码移到了过滤器中,因此所有身份验证检查以及异常都在过滤器中进行处理。但这我不知道该怎么办。
您可以使用依赖项注入。
解决方案取决于您使用的是ServiceFilter
还是TypeFilter
:
使用ServiceFilter
时>:
1)将消息数据注册为服务
public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<MessageDataService>(); ... }
2)解决属性构造函数中的依赖性
public class TheFilter : IActionFilter { private readonly MessageDataService _messageData; public ThrottleFilter(MessageDataService messageData) { _messageData = messageData; } ... }
3)使用ServiceFilter属性
,不需要点1。[ServiceFilter(typeof(TheFilter))]
[当使用TypeFilter时
来源:
Dependency Injection in action filters in ASP.NET Core
ServiceFilter and TypeFilter - what is the difference in injection those filters?