1
我有AuthActivityAttribute類。這個類的目的是授權用戶有權執行特定的活動。自定義屬性C#不工作
屬性類:
[AttributeUsage(AttributeTargets.All)]
public class AuthActivityAttribute : Attribute
{
#region Properties
public string ActivityName { get; set; }
#endregion
#region Constructor
public AuthActivityAttribute()
{
}
#endregion
#region MemberFunctions
private List<aspnetactivities> GetUserActivities(ApplicationUser currentUser)
{
IList<string> roles = DALAccessObjectObj.UserDALObj.GetUserRoles(currentUser);
List<aspnetactivities> lstAspnetActivites = new List<aspnetactivities>();
foreach (string role in roles)
{
List<aspnetactivities> activities = DALAccessObjectObj.UserDALObj.GetRoleActivity(role);
lstAspnetActivites.AddRange(activities);
}
return lstAspnetActivites;
}
public void ValidateUserActivity()
{
DALAccessObjectObj.UserDALObj = new UserDAL();
ApplicationUser currentUser = DALAccessObjectObj.UserDALObj.GetUserById(HttpContext.Current.User.Identity.GetUserId());
if (GetUserActivities(currentUser).Where(r => r.ActivityName.Equals(ActivityName, StringComparison.InvariantCultureIgnoreCase)
).Select(r => r).Count() > 0)
{
throw new Exception(string.Format("User is not allowed to perform activity named : {0}", ActivityName));
}
}
#endregion
}
我有一個帳戶控制器類。我所需要的只是如果允許他進行註冊活動,用戶只能註冊。但是,當我發送請求的屬性不驗證任何事情。請讓我知道我錯過了什麼或什麼?
類裝飾有屬性
public class AccountController : BaseApiController
{
[AuthActivityAttribute(ActivityName = "Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
// do something ...
}
}
例如:我們把驗證像屬性[的MaxLength(10)],以便它驗證該屬性的長度必須小於10或授權在C#屬性。就像只有管理員可以訪問特定的方法。所以這是我需要實現的東西
[Authorize("Administrator")]
public void DeleteUser()
{
// do something
}
我想要什麼?
[AuthActivity("DeleteUser")]
public void DeleteUser()
{
// do something
}
那麼你期望使用該屬性來執行驗證?什麼是'PlanhayAttributeBase'? –
親愛的@JonSkeet請再次檢查我編輯它。 –
那麼,你已經改變了基類。您仍然沒有解釋爲什麼您期望該屬性自動執行某些操作。屬性不會神奇地讓代碼執行 - 某些事物必須*找到*所有相關的屬性並相應地採取行動。你希望在你的情況下做什麼? –