问题描述
我创建了一个动作过滤器来根据传入的 id 检查 id 是否正确。 过滤器的构造方法接受一个服务类型参数。
在 ActionMethod 运行之前,我需要服务来检查此 ID。但是 GetService()
方法返回 null。
ActionFilter
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);
}
}
ActionMethod
[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>();
解决方法
IUserService
已注册为服务
services.AddScoped<IUserService,UserManager>();
但您正在尝试解决显示属性中的实现 UserManager
[ContainsFilter(typeof(UserManager),typeof(User),IdSections.FromRoute)]
打电话
[ContainsFilter(typeof(IUserManager),IdSections.FromRoute)]
代替