在 ApiController 操作中获取当前用户,而不将 userID 作为参数传递

如何在一个安全的 ApiController 操作中获取当前用户,而不将 userName 或 userId 作为参数传递?

我们假设这是可用的,因为我们处于一个安全操作之中。处于安全操作中意味着用户已经进行了身份验证,并且请求具有其持有者令牌。假设 WebApi 已经授权了用户,那么可能存在一种内置的方式来访问 userId,而不必将其作为操作参数传递。

155980 次浏览
string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
userId = HttpContext.Current.User.Identity.GetUserId();
}

Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.

// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);

See also:

How to access HTTPContext from within your Web API action

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Hint lies in Webapi2 auto generated account controller

Have this property with getter defined as

public string UserIdentity
{
get
{
var user = UserManager.FindByName(User.Identity.Name);
return user;//user.Email
}
}

and in order to get UserManager - In WebApi2 -do as Romans (read as AccountController) do

public ApplicationUserManager UserManager
{
get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
}

This should be compatible in IIS and self host mode

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

If you are using Asp.Identity UseManager, it automatically sets the value of

RequestContext.Principal.Identity.GetUserId()

based on IdentityUser you use in creating the IdentityDbContext.

If ever you are implementing a custom user table and owin token bearer authentication, kindly check on my answer.

How to get user context during Web Api calls?

Hope it still helps. :)

None of the suggestions above worked for me. The following did!

HttpContext.Current.Request.LogonUserIdentity.Name

I guess there's a wide variety of scenarios and this one worked for me. My scenario involved an AngularJS frontend and a Web API 2 backend application, both running under IIS. I had to set both applications to run exclusively under Windows Authentication.

No need to pass any user information. The browser and IIS exchange the logged on user credentials and the Web API has access to the user credentials on demand (from IIS I presume).

In .Net Core use User.Identity.Name to get the Name claim of the user.