简体   繁体   中英

Get current http context user in .Net Core 2.0 WebAPI controller

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM