C# ActionFilterAttribute中的GetService返回null
我创建了一个操作过滤器,根据传入的id检查id是否正确。 筛选器的构造函数方法采用服务类型参数 我需要服务在ActionMethod运行之前检查此id。但是C# ActionFilterAttribute中的GetService返回null,c#,asp.net-core,asp.net-core-webapi,actionfilterattribute,C#,Asp.net Core,Asp.net Core Webapi,Actionfilterattribute,我创建了一个操作过滤器,根据传入的id检查id是否正确。 筛选器的构造函数方法采用服务类型参数 我需要服务在ActionMethod运行之前检查此id。但是GetService()method返回null ActionFilter public class ContainsFilterAttribute : ActionFilterAttribute { private Type _service; private Type _entity; private IdSec
GetService()
method返回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);
}
}
行动方法
[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);
}
[HttpGet]
[路由(“{userId}/用户通道”)]
[ContainsFilter(typeof(UserManager)、typeof(User)、IdSections.FromRoute)]
公共IActionResult GetUserChannel(int userId)
{
var result=\u channelService.GetUserChannels(userId);
如果(结果:IsSuccessful)
{
var mapreult=_mapper.Map(result.Data);
返回Ok(映射结果);
}
返回此.ServerError(result.Message);
}
注射
services.AddScoped<IUserService, UserManager>();
services.addScope();
IUserService
已注册为该服务
services.AddScoped<IUserService, UserManager>();
召唤
反而
[ContainsFilter(typeof(UserManager), typeof(User), IdSections.FromRoute)]
[ContainsFilter(typeof(IUserManager), typeof(User), IdSections.FromRoute)]