如何在 Web API 中使用“User.Identity.IsAuthenticated”

use*_*759 5 c# asp.net-mvc asp.net-web-api

User.Identity.IsAuthenticated总是false在我的 ASP.NET Web API 项目中返回。

在帐户中,ApiController我有以下内容:

ClaimsIdentity identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); 
AuthenticationManager.SignIn(new AuthenticationProperties() { 
    IsPersistent = isPersistent 
}, identity);
Run Code Online (Sandbox Code Playgroud)

登录后,User.Identity.IsAuthenticated总是falseApiControllertrue在 MVC 控制器中。

OzB*_*Bob 6

ApiController有一个用户属性,可从:

base.User.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果未通过身份验证,base.User 可以为 null (2认同)

Ham*_*den 2

它无法直接在 APIControiller 中使用 HttpContext 属性。要获得此信息,您必须使用 System.Net.Http.HttpRequestMessage 类型的 Request 属性。HttpRequestMessage有一个Properties字典;您会发现 MS_UserPrincipal 键的值保存着您的 IPrincipal 对象。