【问题标题】:GetService in ActionFilterAttribute returns nullActionFilterAttribute 中的 GetService 返回 null
【发布时间】: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


    【解决方案1】:

    IUserService 注册为服务

    services.AddScoped<IUserService, UserManager>();
    

    但您正在尝试解决显示属性中的实现UserManager

     [ContainsFilter(typeof(UserManager), typeof(User), IdSections.FromRoute)]
    

    打电话

    [ContainsFilter(typeof(IUserManager), typeof(User), IdSections.FromRoute)] 
    

    改为

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多