2017-04-10 66 views
-1

我正在尝试获取web api控制器中的登录用户。当我这样做时c#身份在api控制器中获取登录用户

User.Identity.GetUserId(); 

它返回null。

但我的用户已登录。任何人都知道是什么问题?

这是我使用的API类

using AltuaWebsite.Core.Models; 
using System; 
using System.Web; 
using System.Web.Http; 

这是怎么了用户在系统登陆

public ActionResult Login(String email, String password) 
{ 
    ApplicationUser user = UserManager.FindByName(email); 

    if (user != null && checkRole("admin,user", user.Id) && UserManager.CheckPassword(user, password)) 
    { 
     var identity = new ClaimsIdentity(new[] { 
        new Claim(ClaimTypes.Name, email) 
       }, 
       DefaultAuthenticationTypes.ApplicationCookie, 
       ClaimTypes.Name, ClaimTypes.Role); 

     foreach (var role in user.Roles) 
     { 
      identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); 
     } 

     Authentication.SignIn(new AuthenticationProperties 
     { 
      IsPersistent = true, 
      ExpiresUtc = DateTime.UtcNow.AddHours(24) 
     }, identity); 

     return RedirectToAction("Index", "Dashboard"); 
    } 
    else 
    { 
     return RedirectToAction("Index", "Site"); 
    } 
} 
+0

你使用System.Web.Http添加了吗? –

+0

他们是如何登录的?在你的应用程序中登录表单? NT认证,基本认证? – BugFinder

+1

请阅读[问]并显示你的尝试。首先解释你正在使用的认证。 – CodeCaster

回答

0

您也可以尝试直接按照您的控制器是什么

var claimsPrincipal = (ClaimsPrincipal)ActionContext.RequestContext.Principal;