【发布时间】:2021-09-04 15:45:31
【问题描述】:
对于一个学校项目,我正在重新制作 Top2000 网站(荷兰网站,每年有 2000 首最受欢迎的歌曲)。现在我的角色和授权有问题。
我想添加一个管理员角色并仅授予具有该角色的用户访问隐私页面的权限。 这是我到目前为止得到的: Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<db_a74225_top2000Context>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
HomeController.cs
namespace Top2000.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Screenshot of dbo.AspNetUserRoles
我希望进入隐私页面,但当我登录时,我仍然收到拒绝访问。
【问题讨论】:
-
Startup:Configure方法中有app.UseAuthentication和app.UseAuthorization()吗? -
是的,我有这个顺序。我会将其附加到我的问题中。
-
嗨@Samball,有关于这个案例的最新消息吗?
-
@Yinqiu 现在可以了,谢谢你的帮助!
标签: c# asp.net asp.net-mvc asp.net-core authorization