我正在使用Entity Framework 5 Database First方法开发一个MVC 5 web应用程序.我使用OWIN对用户进行身份验证.下面显示了我在帐户控制器中的登录方法.

public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
        if (user != null)
        {
            var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

            identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person"));
            identity.AddClaim(new Claim(ClaimTypes.Sid, user.userID)); //OK to store userID here?

            AuthenticationManager.SignIn(new AuthenticationProperties
            {
                IsPersistent = model.RememberMe
            }, identity);

            return RedirectToAction("Index", "MyDashboard");
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password.");
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

如您所见,我创建了一个ClaimsIdentity并向其添加了几个声明,然后使用AuthenticationManager将其传递给OWIN以执行登录.

The problem I am having is that I'm not sure how to access the claims in the rest of my application, either in Controllers or in Razor Views.

我try 了本教程中列出的方法

http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

例如,我在控制器代码中try 了这一点,试图访问传递到声明中的值,但是,用户.索赔等于零

var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;

也许我错过了什么.

UPDATE

根据Darin的回答,我添加了他的代码,但我仍然看不到访问声明的权限.请看下面的屏幕截图,其中显示了当我将鼠标悬停在身份上方时看到的内容.声明.

在此处输入图像描述

推荐答案

试试这个:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

Asp.net相关问答推荐

由于 Blazor Change Detection API,组件重新渲染被跳过.如何避免?

我们可以在一个网页中使用多个表单吗?

.Net Framework:w3wp.exe 中的异常

如何在页面加载之前运行 JavaScript 代码?

asp.net:与其中的用户控件相比,控件/页面的页面生命周期顺序是什么?

Automapper - 映射器已初始化错误

IIS 将旧用户名返回到我的应用程序

System.Web.Helpers.Crypto - 盐在哪里?

如何缓存数据库表以防止在 Asp.net C# mvc 中出现许多数据库查询

如何从 RouteData 获取路由名称?

从 RowDataBound 事件的 gridview 从单元格中获取值

System.Linq.Dynamic 不支持 OrderByDescending("someColumn")?

您对 Windows Workflow Foundation 有何体验?

更改后未应用 CSS

ASP.NET 日期时间 Select 器

IIS 中的 existingResponse="PassThrough" 是什么意思?

如何获取 ASP.NET 应用程序的完整虚拟路径

ContentResult 与字符串

在c#中显示带有换行符的标签文本

如何清除 System.Runtime.Caching.MemoryCache