如何解决ActionFilterAttribute 中的 GetService 返回 null
我创建了一个动作过滤器来根据传入的 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)]
代替
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。