For simplification in an asp.net webapi controller , it is good to use a Principal object (authenticated User Object) as a property or variable that should set in controller constructor. but User is null in constructor. how can i get current user in controller constructor ?
为了简化asp.net webapi控制器,最好使用Principal对象(经过身份验证的用户对象)作为应在控制器构造函数中设置的属性或变量。但是User在构造函数中为null。如何在控制器构造函数中获取当前用户?
public class MyController : ApiController
{
string userId;
public MyController()
{
userId = User.Identity.GetUserId();
}
public IEnumerable<string> Get()
{
var userName = GetUserNameById(userId);
return new string[] { userName };
}
}
1 个解决方案
#1
0
The user is assigned well after the controller has been created. You wont be able to access it in the constructor. Instead you should get the user id directly in your actions after the request and associated user have been assigned to the controller.
在创建控制器后,用户分配得很好。您将无法在构造函数中访问它。相反,在请求和关联用户已分配给控制器后,您应该直接在操作中获取用户ID。
public class MyController : ApiController
{
private string GetUserId() {
return User.Identity.GetUserId();
}
public IEnumerable<string> Get()
{
var userName = GetUserNameById(GetUserId());
return new string[] { userName };
}
}
#1
0
The user is assigned well after the controller has been created. You wont be able to access it in the constructor. Instead you should get the user id directly in your actions after the request and associated user have been assigned to the controller.
在创建控制器后,用户分配得很好。您将无法在构造函数中访问它。相反,在请求和关联用户已分配给控制器后,您应该直接在操作中获取用户ID。
public class MyController : ApiController
{
private string GetUserId() {
return User.Identity.GetUserId();
}
public IEnumerable<string> Get()
{
var userName = GetUserNameById(GetUserId());
return new string[] { userName };
}
}