自定义成员资格提供程序
要创建自定义成员资格提供程序,继承 MembershipProvider 抽象类并重写 ValidateUser 方法以根据您的预期数据源验证用户凭据。请考虑以下示例:
public class MyMembershipProvider : MembershipProvider { public override bool ValidateUser(string username, string password) { // Validate user credentials against your database here. var oUserProvider = new MyUserProvider(); return oUserProvider.ValidateUser(username,password,CurrentTerritoryID); } }
通过添加引用并在 web.config 中配置该提供程序将其集成到 ASP.NET MVC 2 中:
<membership defaultProvider="MyMembershipProvider"> <providers> <clear /> <add name="MyMembershipProvider" applicationName="MyApp" Description="My Membership Provider" passwordFormat="Clear" connectionStringName="MyMembershipConnection" type="MyApp.MyMembershipProvider" /> </providers> </membership>
自定义角色提供程序
对于基于角色的授权,创建一个继承 RoleProvider 抽象类并重写GetRolesForUser 方法。
public override string[] GetRolesForUser(string username) { // Fetch user roles from the database here. SpHelper db = new SpHelper(); DataTable roleNames = null; try { roleNames = db.ExecuteDataset(ConnectionManager.ConStr, "sp_GetUserRoles", new MySqlParameter("_userName", username)).Tables[0]; } catch (Exception ex) { throw ex; } string[] roles = new string[roleNames.Rows.Count]; int counter = 0; foreach (DataRow row in roleNames.Rows) { roles[counter] = row["Role_Name"].ToString(); counter++; } return roles; }
在 web.config 中配置角色提供者:
<system.web> ... <roleManager enabled="true" defaultProvider="MyRoleProvider"> <providers> <clear /> <add name="MyRoleProvider" applicationName="MyApp" type="MyApp.MyRoleProvider" connectionStringName="MyMembershipConnection" /> </providers> </roleManager> ... </system.web>
授权
使用 [Authorize(Roles= “xxx,yyy”)] 属性来保护特定的控制器和操作
自定义授权属性(可选)
要将未经授权的用户重定向到 AccessDenied 页面,请创建自定义 [MyAuthorization] 属性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class MyAuthorizationAttribute : AuthorizeAttribute { // ... Implementation }
按如下方式使用该属性:
[MyAuthorization(Roles = "Portal Manager,Content Editor", ViewName = "AccessDenied")] public class DropboxController : Controller { ....... }
以上是如何在 ASP.NET MVC 2 中实现自定义成员资格和角色提供程序?的详细内容。更多信息请关注PHP中文网其他相关文章!