[英]Roles asp.net settings
我目前正在使用ASP.NET MVC 4
开发应用程序,但我也在学习。
我想使用角色进行身份验证,但是我做错了。
关键是我不需要更多角色,我只想要默认角色。
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<roleManager enabled="true" />
在控制器
[Authorize(Roles = "Administrator")]
public class AccountController : Controller
{}
在LogIn post方法中,我想将用户添加到该角色。
if (!Roles.IsUserInRole(saveAccount.Username, "Administrators"))
Roles.AddUserToRole(saveAccount.Username, "Administrators");
但是每次我登录并尝试重定向到另一个页面时,都会收到此提示
HTTP Error 401.0 - Unauthorized You do not have permission to view this directory or page.
有人可以引导我吗?
将用户添加到角色时,必须使用UserId,而不是用户名。
您还必须在Roles表中创建一个记录,其中包含所需角色的名称。
使用RoleManager创建新角色。
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
if (!roleManager.RoleExists("Admin"))
{
//Creating Admin role
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Administrator";
roleManager.Create(role);
}
if (!Roles.IsUserInRole(#yourUserId, "Administrator")) {
Roles.AddUserToRole(#yourUserId, "Administrator");
}
(您的用户和角色的数据库在Server Explorer的Data Connections区域中的DefaultConnection下)。
角色是授权,身份验证是另一个过程。
如果您只需要限制已知用户,则:
<system.web>
上实施表单身份验证 。
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<authentication mode="Forms">
<forms all parameters needed to a connection's forms></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.