我有AuthActivityAttribute类。此类的目的是授权用户具有执行特定活动的权限。
属性类:
[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属性。只有管理员可以访问特定的方法。所以这是我需要实现的目标
[Authorize("Administrator")]
public void DeleteUser()
{
// do something
}
我想要什么?
[AuthActivity("DeleteUser")]
public void DeleteUser()
{
// do something
}
答案 0 :(得分:0)
如果您的目标是让用户执行或不执行任务,则无需为每个操作创建自定义属性,您可以使用“授权”属性,并指定允许执行该操作的角色。
无论如何,如果要使用自定义属性执行某些自定义任务,则必须使用反射来获取具有该属性的操作并获取该属性的属性,如:
public static class CustomAttrr
{
public static IEnumerable<ActionsWithAuthActivityAttribute> GetItems(Assembly types)
{
var model = from type in types.GetTypes()
from methodInfo in type.GetMethods().Where(x => x.GetCustomAttributes<AuthActivityAttribute>().Any())
from attribute in methodInfo.GetCustomAttributes()
where attribute is AuthActivityAttribute
let a = attribute as AuthActivityAttribute
select new ActionsWithAuthActivityAttribute
{
ActionName = methodInfo.Name,
ActivityName = a.ActivityName,
};
return model.ToList();
}
}
public class AuthActivityAttribute:Attribute
{
public string ActivityName { get; set; }
}
public class ActionsWithAuthActivityAttribute
{
public string ActionName { get; set; }
public string ActivityName { get; set; }
}
现在,您有一个使用您的属性装饰的所有操作的列表,您可以随心所欲地执行操作。
var listAction = CustomAttrr.GetItems(Assembly.GetExecutingAssembly());
var listActionsRegister = listAction.Where(x => x.ActivityName.Equals("Register"));
现在您可以检查用户角色与此列表,但就像我说的那样,您不需要此自定义属性。
我发布此代码仅供您查看如何访问自定义属性。