【发布时间】:2018-07-31 04:45:10
【问题描述】:
我正在尝试设置 Hangfire,以便只有管理员用户可以访问仪表板。我的 User 模型有一个属性 UserRole 可以与父枚举进行比较。
但是,我对如何从 Startup.cs 中将 DataContext 传递到授权过滤器感到困惑。
我应该以其他方式尝试访问 User 对象吗?
(我用的是实体框架)
Startup.cs
public void Configure(IApplication app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
{
//ERROR here because I'm not passing in DataContext,
//but I'm not sure how to do that...
Authorization = new [] { new HangfireAuthorizationFilter() }
});
app.UseHangfireServer();
...
}
public class HangfireAuthorizationFilter : Controller, IDashboardAuthorizationFilter
{
private readonly DataContext _context;
public HangfireAuthorizationFilter(DataContext context)
{
_context = context;
}
public bool Authorize([NotNull] DashboardContext context)
{
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
try {
var userFromRepo = _context.Users.First(u => u.Id == currentUserId);
return userFromRepo.UserRole == UserRole.Admin;
catch {
return false;
}
}
}
【问题讨论】:
-
我应该将用户保存到 cookie 并以某种方式检索它吗?
-
你为什么要使用hangfire .Net-core 已经通过HostedServices 内置了对后台服务的支持
-
我的经理喜欢使用 hangfire 仪表板。但我肯定会调查 HostedServices
-
好吧,我只是想让你知道还有其他选择 ;)
标签: c# asp.net-core hangfire