我想引入一个自定义操作过滤器,以检查数据库中记录的存在。
如果用户记录存在,那么我希望操作正常进行。但是,如果记录不存在,那么我想重定向到特定的操作/控制器,以强制他们创建记录。
据我了解,我需要完成以下工作:
创建存储在mvc项目中的动作过滤器
命名空间Skillray.TachoHub.Web.ActionFilter { 公共类BulletinActionFilter:IAsyncActionFilter,ITransientDependency { 私有只读IRepository _bulletinRepository; 私有只读IAbpSession _session;
public BulletinActionFilter(IRepository<Entities.Bulletin.Bulletin> bulletinRepository,
IAbpSession session)
{
_bulletinRepository = bulletinRepository;
_session = session;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var userId = _session.UserId;
if (userId != null)
{
var bulletinList = _bulletinRepository.GetAll().Where(x => x.ForceWarningOn < DateTime.Now)
.Include(x=>x.Consent)
.ToList();
foreach(var b in bulletinList)
{
if(b.Consent.Any(x=>x.UserId == userId))
{
return RedirectToAction("View", "Bulletin", new { Id = b.Id });
}
}
}
await next();
}
}
}
}
在startup.cs中添加过滤器
services.AddMvc(options => { options.Filters.Add(new BulletinActionFilter()); });
上述问题是BulletinActionFilter期望为存储库和会话传递参数。我不确定最好的进行方式,因为我通常可以分别在类中注入存储库和会话。