自訂成員資格提供程式
要建立自訂成員資格提供程序,繼承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中文網其他相關文章!