【问题标题】:Get current http context user in .Net Core 2.0 WebAPI controller在 .Net Core 2.0 WebAPI 控制器中获取当前的 http 上下文用户
【发布时间】:2019-01-03 09:30:38
【问题描述】:

我有一个 .Net Core 2 WebAPI 控制器,需要在它的构造函数或其中一个路由中检索当前用户 ID。

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

上面的WindowsIdentity.GetCurrent().Name 不会给我我需要的东西。我想我需要一个相当于 .Net 框架的 System.Web.HttpContext.Current.User.Identity.Name

有什么想法吗? 请注意,这是一个 .Net Core 2.0 WebAPI,请不要为常规 .net 控制器提供解决方案。

【问题讨论】:

    标签: c# .net-core asp.net-core-webapi httpcontext


    【解决方案1】:

    ControllerBase.User 将持有请求的当前经过身份验证的用户的原则,并且仅在执行操作的范围内可用,而不是在构造函数中。

    [HttpGet("[action]")]
    public AppSettings GetAppSettings() {
        var user = this.User;
        var appSettings = new AppSettings {
            //Other settings
            CurrentUser = user.Identity.Name
        };
        return appSettings;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多