简体   繁体   中英

Custom attributes C# not working

I have AuthActivityAttribute class. the purpose of this class is to authorize that the user have permission to perform specific activity.

Attribute Class :

[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

}

I have a Account controller class. All I need is user can only be registered if he is allowed to perform registration activity. However when i send the request the attribute does not validate any thing . Please let me know am i missing something or what ?

Class decorated With Attribute

  public class AccountController : BaseApiController
    {
        [AuthActivityAttribute(ActivityName = "Register")]
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            // do something ...
        }
    }

for example : we put validation on property like [MaxLength(10)] so it validates that the property must have length less than 10. or Authorize attribute in C#. like only admin can access the specific method. So this is something i need to achieve

[Authorize("Administrator")]
public void DeleteUser()
{
// do something
}

What i want ?

[AuthActivity("DeleteUser")]
public void DeleteUser()
{
// do something
}

If your goal is to let or not the user to perform a task, you don't need to create a custom attribute, you can use Authorize attribute, for each action and specify the Roles which are allowed to execute that action.

Any way, if you want to perform some custom task using a custom attribute, you must use reflection to get the actions which has that attribute and to get the properties of that attribute, something like:

    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; }
}

Now, you have a list of all actions decorated with your attribute, and you can do what ever you want.

  var listAction = CustomAttrr.GetItems(Assembly.GetExecutingAssembly());
  var listActionsRegister = listAction.Where(x => x.ActivityName.Equals("Register"));

Now you can check user role versus this list, but like I said, you do not need this custom attribute.

I posted this code only for you to see how to access the custom attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM