c# - ActionFilterAttribute 中的 GetService 返回 null

标签 c# asp.net-core asp.net-core-webapi actionfilterattribute

我创建了一个 Action 过滤器来根据传入的id检查id是否正确。 过滤器的构造方法采用服务类型参数。

我需要服务在 ActionMethod 运行之前检查此 id。但是 GetService() 方法返回 null。

Action 过滤器

 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);
    }

注入(inject)

services.AddScoped<IUserService, UserManager>();

最佳答案

IUserService 已注册为服务

services.AddScoped<IUserService, UserManager>();

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

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

通话

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

相反

关于c# - ActionFilterAttribute 中的 GetService 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66427642/

相关文章:

c# - 是否可以使用外部 AD 从 Azure 托管的 Web 应用程序进行身份验证?

c# - 在 ASP.NET 中识别用户所属的租户

c# - 检测 Entity Framework 4.0 中 ObjectSet 的变化?

log4net - ASP.Net Core 2.0 Web Api 设置 log4net

json - Swagger 文档中的驼峰命名法

c# - System.Diagnostics.StackTrace 紧凑框架

visual-studio-2015 - 从 ASP.Net 5 项目中彻底删除 Bower

jenkins - 在 docker 容器中使用 Jenkins 构建 ASP.NET 5

asp.net-core - .Net Core 中的 Big-Endian 处理

Azure AAD - 受众无效