How to check user is in many roles in asp.net identity

橙三吉。 提交于 2019-11-29 15:43:22

Well I found a way to do it. I didn't know User object that returns by UserManager has Roles property with the collection of roles that the user has.

using Microsoft.AspNet.Identity;
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

var roles = new List<string> { "admin", "contributor" };
var currentUser = manager.FindById(User.Identity.GetUserId());  

if (currentUser.Roles.Any(u => roles.Contains(u.Role.Name)))
{

}     

More information on Asp.net Identity membership .. this seems like good resource.

http://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples/

Well I guess it all depends on what your requirements are i.e. use simple membership if you can. IF you integrate the membership correctly (Forms Authentication) then you should really use User.IsInRole("Role").

It looks like by what you have posted that you are using your own custom user objects so in this scenario i would use a custom membership provider there are lots of examples of this on the net here the first 1 i found http://www.codeproject.com/Articles/165159/Custom-Membership-Providers

The idea is to just override all the Membership methods and return your own user data from your service layer.

Hope that helps. Lee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!