我创建了一个动作过滤器,根据传入的id检查id是否正确。过滤器的构造函数方法接受一个服务类型参数。
我需要服务来检查这个id在ActionMethod运行之前。但是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), typeof(User), IdSections.FromRoute)]
而不是