Tôi biết đây là một bài đăng cũ nhưng tôi nghĩ rằng tôi sẽ chia sẻ kinh nghiệm của mình khi tôi thực hiện điều này. Tôi không muốn sử dụng web.config. Tôi đã tìm cách tạo một thuộc tính cho các biểu mẫu web tương tự như việc triển khai MVC. Tôi đã tìm thấy một bài đăng theo số Deran Schilling mà tôi đã sử dụng làm cơ sở cho phần thuộc tính.
Tôi tạo ra một IPrincipal
interface IMyPrincipal : IPrincipal
{
string MyId { get; }
string OrgCode { get; }
string Email { get; }
}
và Principal
public class MyPrincipal : IMyPrincipal
{
IIdentity identity;
private List<string> roles;
private string email;
private string myId;
private string orgCode;
public MyPrincipal(IIdentity identity, List<string> roles, string myId, string orgCode, string email)
{
this.identity = identity;
this.roles = roles;
this.myId = myId;
this.orgCode = orgCode;
this.email = email;
}
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
return roles.Contains(role);
}
public string Email
{
get { return email; }
}
public string MyId
{
get { return myId; }
}
public string OrgCode
{
get { return orgCode; }
}
}
tùy chỉnh và tạo ra một thuộc tính để sử dụng trên các trang
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AdminAuthorizationAttribute : Attribute
{
public AdminAuthorizationAttribute()
{
var user = (MyPrincipal)HttpContext.Current.User;
if (user.IsInRole("MyAdmin"))
return;
throw new AccessDeniedException();
}
}
và tạo ra một số trường hợp ngoại lệ tùy chỉnh
public class AccessDeniedException : BaseHttpException
{
public AccessDeniedException() : base((int)HttpStatusCode.Unauthorized, "User not authorized.") { }
}
public class BaseHttpException : HttpException
{
public BaseHttpException(int httpCode, string message) : base(httpCode, message) { }
}
và bây giờ tôi có thể áp dụng các thuộc tính để sử dụng trên một trang nhất định
[AdminAuthorization]
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
đúng tôi đó. Nhưng có cách nào để hạn chế truy cập ở một mức độ phương pháp cụ thể tương tự như cách bạn có thể làm điều đó với MVC? –
@Blair Jones, bạn sẽ phải thực hiện kiểm tra như 'if (User.IsInRole (" somerole "))' trong phương thức, tôi sợ. –
ok cảm ơn ... đó là những gì tôi đã sợ: ( –