Asp.net web api ApiController中的UserManager

Asp.net web api ApiController中的UserManager,asp.net-web-api,asp.net-identity,Asp.net Web Api,Asp.net Identity,在我的项目中,HttpContext是Controller的成员,我可以在AccountController:Controller中使用它。但我无法在ApiController中访问有关当前用户的信息 公共类AccountController:ApicController { 公共用户管理器用户管理器{get;private set;} 专用IAAuthenticationManager AuthenticationManager { 收到 { 返回HttpContext.Current.Get

在我的项目中,HttpContext是Controller的成员,我可以在AccountController:Controller中使用它。但我无法在ApiController中访问有关当前用户的信息

公共类AccountController:ApicController
{
公共用户管理器用户管理器{get;private set;}
专用IAAuthenticationManager AuthenticationManager
{
收到
{
返回HttpContext.Current.GetOwinContext().Authentication;
}
}
}
那么,如何编写自定义ApiController呢

在下面的方法中,用户变量在断点上显示null。如果我知道hi已登录,如何检索当前用户

    public IHttpActionResult GetUser(int id)
    {
        var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var userid = User.Identity.GetUserId();
        var user = manager.FindById(userid);

        var data = new Person {Name = user.UserName, Age = 99};

        return Ok(data);
    }
public IHttpActionResult GetUser(int id)
{
var manager=HttpContext.Current.GetOwinContext().GetUserManager();
var userid=User.Identity.GetUserId();
var user=manager.FindById(userid);
var data=newperson{Name=user.UserName,年龄=99};
返回Ok(数据);
}

在任何控制器方法中,您都可以执行此操作。GetRequestContext().User以获取当前经过身份验证的用户。WebApi不支持静态HttpContext.Current。

manager.FindById(userid)从数据库而不是当前数据库检索用户。要获取当前用户,只需访问ApicController中的user属性:

public class MyApiController : ApiController
{
    IPrincipal GetCurrentUser(){
        return User;
    }
}
这可能会帮助您:

protected string UserId { get { return User.Identity.GetUserId(); } }

你好完整方法是什么?抱歉,IntelySense没有在ApicController子级中显示任何GetRequestContext()方法;是否为空?这也返回空值:string userEmail=RequestContext.Principal.Identity.Name;