c# - 用户登录后缓存用户信息

标签 c# entity-framework authentication caching asp.net-mvc-5

我有不同角色的用户。我想根据用户的角色提供受限制的 View 。我的代码中有一些检查角色的东西:

bool isAdmin = UserManager.IsInRole(currentUser.Id,"admin");
bool isEmployee = UserManager.IsInRole(currentUser.Id,"employee");

要使上述代码正常工作,我需要实例化 currentUser。换句话说,我需要捕获当前登录用户的信息。我尝试了类似 var user = User.Identity.GetUserId(); 和许多其他但找不到工作代码。我将不胜感激任何帮助。谢谢!

更新:

这是我的完整方法代码。在我检查上面的例子之前,你们可能都想看看。

public ActionResult Index()
{ 
    var user = User.Identity.GetUserId(); 
    bool isAdmin = UserManager.IsInRole(user, "admin"); 
    bool isEmployee = UserManager.IsInRole(user, "employee"); 
    if (isAdmin)
    { 
        return View(db.Customers.ToList()); 
    }
    else
    { 
        var restricted = db.Customers.Where(c => c.FirstName == "John");
        return View(restricted); 
    } 
} 

最佳答案

[Authorize] 属性应在所需的受限 actionController 方法中实现。示例如下。

 [Authorize(Roles="Admin")]
public ActionResult Index()
        {
            return View();
        }

此 Controller 方法仅限于具有管理员角色的用户。此外,相同的 Action Controller 方法可以使用不同的授权标签包含两次。

关于c# - 用户登录后缓存用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179496/

相关文章:

c# - 如何以 DateTime 格式显示双倍 (HH :mm:ss)?

c# - 如何覆盖 XAMARIN.FORMS 的加载 View

c# - Xamarin 安卓 : What is the correct way to Marshal a string from C# to a Unicode string in C++?

entity-framework - Entity Framework ,代码优先,更新 "one to many"与独立关联的关系

HTTP 数据包,发生了什么?

c# - 在 MonoGame 中运行时加载 MGCB?

java - 如何使用 JPA 2.1 转换连接的元素集合?

c# - RIA 服务/EF。对派生类中 bool 字段的更改不会保存到数据库

php - 使用 OAuth2 在 laravel 中自定义用户提供程序

java - 在 Spring 中验证每个请求和响应的用户