Refactoring long if statement that checks for user roles
Hi, I'm trying to find a cleaner way of refactoring this if code block that checks for each user role. The if statement works but looks really messy, and I was wondering if it's possible to do something like how EF Core would do, just check if it contains something using
.Contains()
.
12 Replies
I'd probably create an extension method on
User
Or create some authorization servicenew[]{"Role1",...}.Any(User.IsInRole)
you can move the roles into a static readonly field to make sure it's not allocated multiple timesHmm, extension method?
Yeah
In case you didn't know what extension methods are...
I'm still confused as in how does this relate to checking for the roles.
You asked what extension methods are... well, this is what they are
You can declare one on your
User
that has all those checks inside
So that you can just do if (User.CustomChecks())
Or just a computed property on the user
User
in this instance is of, I believe, IClaimsPrincipal
, type
It's not an IdentityUser
Yeah, the naming is a bit confusing, but it is what it isAhh okay, I went and try to create the custom extension check in one razor view.... so i was stuck trying to figure out how to do it
Wait, so it's something like
public static bool (this IPrincipal user)
and not public static bool (this User user)
?ye
Does
IsInRole
checks for the entire role name or part of it? Like, if I just specify "Department", does it verify all "Department.A", "Department.B", etc?
how to check for true : false here btw? I'm looking to return false if the second variable is true for example.