【发布时间】:2021-05-31 07:16:22
【问题描述】:
我创建了一个动作过滤器来根据传入的 id 检查 id 是否正确。 过滤器的构造方法接受服务类型参数。
我需要服务在 ActionMethod 运行之前检查这个 id。但是 GetService() 方法返回 null。
动作过滤器
public class ContainsFilterAttribute : ActionFilterAttribute
{
private Type _service;
private Type _entity;
private IdSections _idSections;
public ContainsFilterAttribute(Type service, Type entity, IdSections idSections)
{
if (!typeof(ICommonService).IsAssignableFrom(service) || !typeof(IEntity).IsAssignableFrom(entity))
{
throw new System.Exception("Service or entity undefined.");
}
_service = service;
_entity = entity;
_idSections = idSections;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
//returns null service
var service = (ICommonService)context.HttpContext.RequestServices.GetService(_service);
var entity = (IEntity)Activator.CreateInstance(_entity);
if (IdSections.FromRoute == _idSections)
{
entity.Id = (int)context.ActionArguments.FirstOrDefault(pair => pair.Key.ToUpper().Contains("ID")).Value;
}
var res = service.Contains(entity);
}
}
动作方法
[HttpGet]
[Route("{userId}/user-channels")]
[ContainsFilter(typeof(UserManager), typeof(User), IdSections.FromRoute)]
public IActionResult GetUserChannels(int userId)
{
var result = _channelService.GetUserChannels(userId);
if (result.IsSuccessful)
{
var mapResult = _mapper.Map<List<ChannelForListDto>>(result.Data);
return Ok(mapResult);
}
return this.ServerError(result.Message);
}
注入
services.AddScoped<IUserService, UserManager>();
【问题讨论】:
标签: c# asp.net-core asp.net-core-webapi actionfilterattribute