Reputation: 1023
I have a .Net Core 2 WebAPI controller and need to retrieve the current user Id in either it's constructor or one of the routes.
[Route("api/[controller]")]
public class ConfigController : Controller
{
private readonly IConfiguration _configuration;
public ConfigController(IConfiguration iConfig)
{
_configuration = iConfig;
}
[HttpGet("[action]")]
public AppSettings GetAppSettings()
{
var appSettings = new AppSettings
{
//Other settings
CurrentUser = WindowsIdentity.GetCurrent().Name
};
return appSettings;
}
}
The above WindowsIdentity.GetCurrent().Name
won't give me what I need. I figured I will need an equivalent of the .Net framework's System.Web.HttpContext.Current.User.Identity.Name
Any idea? Please note this is a .Net Core 2.0 WebAPI, please don't suggest solutions for the regular .net controllers.
Upvotes: 0
Views: 1091
Reputation: 247163
The ControllerBase.User
will hold the principle of the currently authenticated user for the request and will only be available in the scope of the executing action, not in the constructor.
[HttpGet("[action]")]
public AppSettings GetAppSettings() {
var user = this.User;
var appSettings = new AppSettings {
//Other settings
CurrentUser = user.Identity.Name
};
return appSettings;
}
Upvotes: 3