C# 在RESTful WebApi方法中检索主体
我不熟悉使用WebApi的RESTful服务。我有一个前端web应用程序,它使用FormsAuthentication对用户进行身份验证。我能够在MVC控制器方法中使用C# 在RESTful WebApi方法中检索主体,c#,angularjs,rest,asp.net-web-api,formsauthentication,C#,Angularjs,Rest,Asp.net Web Api,Formsauthentication,我不熟悉使用WebApi的RESTful服务。我有一个前端web应用程序,它使用FormsAuthentication对用户进行身份验证。我能够在MVC控制器方法中使用User.Identity属性,没有任何问题 但是,我想使用Angular从浏览器调用WebApi中的Restful方法。这些方法中的用户主体出现问题-HttpRequestMessage.GetUserIdentity()始终返回null。相比之下,这些方法中的Thread.CurrentPrincipal正确地返回当前经过身份
User.Identity
属性,没有任何问题
但是,我想使用Angular从浏览器调用WebApi中的Restful方法。这些方法中的用户主体出现问题-HttpRequestMessage.GetUserIdentity()
始终返回null。相比之下,这些方法中的Thread.CurrentPrincipal
正确地返回当前经过身份验证的用户标识。我的WebApi控制器用Authorize
属性修饰
停止GetUserIdentity()
工作时我缺少了什么?这是我的控制器
[Authorize]
public class CategoryController : ApiController
{
public IEnumerable<ICategoryJson> Get(HttpRequestMessage request)
{
var user = request.GetUserPrincipal(); // returns null
var user1 = System.Threading.Thread.CurrentPrincipal; // returns authenticated user identity
return null;
}
}
MVC控制器继承自不同的基类,因此它在MVC控制器而不是Web API中工作 在Web API 2中,您可以使用RequestContext.Principal,也可以在控制器操作中使用Thread.CurrentPrincipal来获取用户身份
我认为这个问题与ajax或angular调用无关。您可以尝试从angular代码调用相同的MVC控制器操作,但它仍应返回用户身份。您在API中何时调用此方法?HttpRequestMessage.GetUserIdentity()我在问题中添加了代码,正确的获取方法是:user=this.user;ApiController的用户属性为您提供主体
$http.get("/api/Category", config).then(function (response) {
Array.prototype.push.apply(service.list, response.data);
service.listLoading = false;
});