![](/img/trans.png)
[英].NET Core Web API HttpContext.User.Claims and HttpContext.User.Identity are always null in Controllers
[英]Web Api User Identity returning null
我以用户身份成功登录,然后该用户就可以访问网站的 [已授权] 部分。 用户名甚至会显示在网站的右上角,因为它们已成功通过身份验证。 但是,当我尝试在我的帖子中获取用户身份以创建新事件时,用户为空。
这是我的登录服务:
login.service('loginService', function ($http, $q) {
var deferred = $q.defer();
this.signin = function (user) {
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
$http.post('Token', 'grant_type=password&username='+user.UserName+'&password='+user.Password, config)
.success(function (data) {
window.location = "/dashboard";
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
});
这是我发布新活动的帖子
[Route("post")]
public HttpResponseMessage PostEvent(EventEditModel ev)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "{ }");
}
try
{
Event DBEvent;
if (ev.EventId > 0)
{
DBEvent = db.Events.Find(ev.EventId);
DBEvent.ModifiedBy = Guid.Parse(User.Identity.GetUserId());
DBEvent.ModifiedOn = DateTime.Now;
}
else
{
DBEvent = new Event();
string id = User.Identity.GetUserId();
DBEvent.CreatedBy = Guid.Parse(User.Identity.GetUserId());
DBEvent.CreatedOn = DateTime.Now;
}
...
}
我应该在每个帖子中传递用户信息吗? 我什至不确定我会怎么做。 或者我只是没有正确登录用户?
我偶然发现并想给出我的解决方案的老问题。 离开邓克的答案,然后找到这篇文章,我得到了答案。 为了从GetUserId()
取回一些东西,您必须使用ClaimTypes.NameIdentifier
类型以及您想要的用户 ID 添加一个新声明:
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
User.Identity.GetUserId()
似乎在 Web Api 中返回 null。 据我所知,您应该改用User.Identity.GetUserName()
。
例如
ApplicationUser user = UserManager.FindByName(User.Identity.GetUserName());
var userId = user.Id;
创建新的 ClaimsIdentity 时,您需要使用ClaimTypes.Name
专门为名称创建一个新的ClaimTypes.Name
。
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.