Tôi có một ứng dụng MVC và tôi đã viết một roleprovider tùy chỉnh cho nó như:MVC tùy chỉnh roleprovider làm thế nào để móc nó lên đến HttpContext.Current.User.IsInRole ("myrole")
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using VectorCheck.Models;
namespace VectorCheck.Security
{
public class MyRoleProvider : RoleProvider
{
private VectorCheckRepository<User> _repository { get; set; }
public MyRoleProvider()
{
_repository = new VectorCheckRepository<User>();
}
public MyRoleProvider(VectorCheckRepository<User> repository)
{
_repository = repository;
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
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)
{
var user = _repository.GetUser(username);
return new string[] { user.Role.Name };
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUser(username);
return string.Compare(user.Role.Name, roleName, true) == 0;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
này hoạt động thực sự tốt với việc hạn chế quyền truy cập vào bộ điều khiển và hành động sử dụng:
[Authorize(Roles = "Administrator")]
phía trên bộ điều khiển hoặc hành động.
Tôi cũng muốn giới hạn truy cập đến một số điều trong giao diện mặc dù sử dụng:
HttpContext.Current.User.IsInRole("Administrator")
Phương pháp này không phải là một phần của roleprovider của tôi mặc dù vậy là không nhận được ghi đè.
Có ai biết cách thực hiện nó cho phương pháp này không?
cung cấp Vai trò của tôi không chứa phương thức IsInRole mặc dù. Nó được kế thừa từ RoleProvider và có phương thức IsUserInRole. – AnonyMouse
Phương thức IsInRole trên HttpContext.Current.User là một kiểu triển khai IPrincipal. khi bạn đã đăng ký RoleProvider và yêu cầu đến từ một người dùng đã được xác thực, IPrincipal sẽ là một cá thể của RolePrincipal. Bạn có thể thấy từ phương thức ở trên mà IsInRole trên RolePrincipal gọi phương thức GetRolesForUser của RoleProvider sao cho đó là phương thức mà bạn cần thiết lập một điểm ngắt để đảm bảo nó được gọi chính xác. –