U には ASP.Net MVC 5 Web サイトがあり、現在のユーザーのロール (存在する場合) を取得し、それに応じて行動したいと考えています。テンプレートの VS 2013 のベータ版の後でも、いくつかの変更に気付きました。私は現在このコードを使用しています:
//in Utilities.cs class
public static IList<string> GetUserRoles(string id)
{
if (id == null)
return null;
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new AppContext()));
return UserManager.GetRoles(id);
}
//and I call it like this:
var roles = Utilities.GetUserRoles(User.Identity.GetUserId());
これは最善のアプローチですか?そうでない場合、何ですか?
編集:
これを使用してロールを作成し、ユーザーをロールに追加しています。
RoleManager.Create(new IdentityRole("admin"));
if (um.Create(user, password).Succeeded)
{
UserManager.AddToRole(user.Id, role);
}