GiG*_*iGi 9 c# asp.net asp.net-mvc asp.net-mvc-4
我是mvc4 asp .net的新手,并且与身份验证和授权相混淆.我们的内部网站从Windows身份验证中获取用户名(HttpContext.Current.User.Identity.Name),如果用户名存在以及用户拥有什么角色,则检查数据库.我想使用全局[Authorize]属性和角色来访问控制器.任何人都可以帮助我如何开始.
现在,我有一个函数,它传递用户名并从数据库中获取用户数据和相关角色,查询数据被添加到模型中.所以,我使用此函数来访问网站,但我想使用相同的在不查询db的情况下检查所有控制器和视图的数据.
mas*_*son 17
您只需要创建自定义角色提供程序.您可以通过创建一个继承System.Web.Security.RoleProvider和覆盖某些成员的类来完成此操作.以下代码可以帮助您入门.throw new NotImplementedException()用你的函数实现替换所有的东西.例如,IsUserInRole您将提供将查询数据库以查看用户是否处于指定角色的代码.
using System.Web.Security;
namespace MyNamespace
{
public class MyRoleProvider : RoleProvider
{
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get; set;
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
throw new NotImplementedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可能不需要实现所有这些.例如,如果您的应用程序不会创建或删除角色,则无需对CreateRole或执行任何操作DeleteRole.
您还需要使用ASP.NET框架注册角色提供程序,以便它知道如何使用它.在web.config下面更新你的喜欢.
<configuration>
<system.web>
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add
name="MyRoleProvider"
type="MyNamespace.MyRoleProvider"
applicationName="MyApplicationName" />
</providers>
</roleManager>
</system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7598 次 |
| 最近记录: |