2

TLDR;我有几乎相同的控制器,它们仅通过使用async/ await(当然还有Task)在本质上有所不同。非异步版本按预期返回当前用户的用户名,但async等效版本不返回。

我想发现的是

  1. 这可能成立的情况
  2. 我可以使用这些工具(除了提琴手)来调查这个

注意:我无法针对 ASP.NET Core 源进行调试,因为尚未授予运行权限Set-ExecutionPolicy(这似乎是构建解决方案所必需的)

这有效:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Baffled.API.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class IdentityController : ControllerBase
    {
        private readonly string userName;

        public IdentityController(IHttpContextAccessor httpContextAccessor)
        {
            userName = httpContextAccessor?.HttpContext?.User.Identity?.Name;
        }

        [HttpGet]
        public IActionResultGetCurrentUser()
        {
            return Ok(new { userName });
        }
    }
}

不起作用

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Baffled.Services;

namespace Baffled.API.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class IssueReproductionController : ControllerBase
    {
        private readonly HeartbeatService heartbeatService;
        private readonly ILogger<IssueReproductionController> logger;
        private readonly string userName;

        public IssueReproductionController(
            HeartbeatService heartbeatService,
            ILogger<IssueReproductionController> logger,
            IHttpContextAccessor httpContextAccessor)
        {
            this.heartbeatService = heartbeatService;
            this.logger = logger;

            userName = httpContextAccessor?.HttpContext?.User?.Identity?.Name;
        }

        [HttpGet]
        public async Task<IActionResult> ShowProblem()
        {
            var heartbeats = await heartbeatService.GetLatest();

            logger.LogInformation("Issue reproduction", new { heartbeats });

            var currentUser = userName ?? HttpContext?.User.Identity?.Name;

            return Ok(new { currentUser, heartbeats.Data });
        }
    }
}

我认为配置是正确的,但为了完整起见,它包含在下面:

程序.cs

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace Baffled.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((_, config) =>
                {
                    config.AddJsonFile("appsettings.json", true, true);
                    config.AddEnvironmentVariables();
                })
                .UseWindowsService()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://*:5002");
                    webBuilder.UseStartup<Startup>().UseHttpSys(Options);
                });

        private static void Options(HttpSysOptions options)
        {
            options.Authentication.AllowAnonymous = true;
            options.Authentication.Schemes =
                AuthenticationSchemes.NTLM | 
                AuthenticationSchemes.Negotiate | 
                AuthenticationSchemes.None;
        }
    }
}

启动.cs

using System;
using System.Net.Http;
using Baffled.API.Configuration;
using Baffled.API.Hubs;
using Baffled.API.Services;
using Baffled.EF;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Serilog;
using Serilog.Events;

namespace Baffled.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<HeartbeatService, HeartbeatService>();

            services.AddHttpContextAccessor();
            services.AddAuthentication(HttpSysDefaults.AuthenticationScheme).AddNegotiate();
            services.AddHttpClient("Default").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseDefaultCredentials = true });
            services.AddControllers();

            var corsOrigins = Configuration.GetSection("CorsAllowedOrigins").Get<string[]>();

            services.AddCors(_ => _.AddPolicy("AllOriginPolicy", builder =>
            {
                builder.WithOrigins(corsOrigins)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
            }));

            services.AddSwagger();
            services.AddSignalR();
            services.AddHostedService<Worker>();
            services.AddResponseCompression();

            // Logging correctly configured here
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseSwagger();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseResponseCompression();
            app.UseCors("AllOriginPolicy");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<UpdateHub>("/updatehub");
            });
        }
    }
}

我已经坐了几个星期,希望能找到解决方案。没有。请帮忙。

编辑

我通过 Windows 服务托管了这个。奇怪的行为似乎是不一致和不确定的。有时我看到我的用户名被退回,但我的同事在遇到有问题的端点时从来没有这样做过。

4

2 回答 2

5

您不应尝试在控制器构造函数中访问特定于 HttpContext 的数据。框架不保证构造函数何时被构造,因此构造函数很可能在IHttpContextAccessor访问当前HttpContext. 相反,您应该仅在控制器操作本身内访问特定于上下文的数据,因为这可以保证作为请求的一部分运行。

使用 时IHttpContextAcccessor,您应该始终HttpContext只在需要查看上下文的那一刻访问它。否则,您很可能正在使用可能导致各种问题的过时状态。

但是,在使用控制器时,您实际上根本不需要使用IHttpContextAccessor。相反,该框架将为您提供多个属性,以便您可以直接在控制器上访问 HttpContext 甚至用户主体(在 Razor 页面和 Razor 视图中,有类似的属性可供使用):

请注意,这些属性在控制器操作中可用,在构造函数中不可用。有关这方面的更多详细信息,请参阅此相关帖子


以您的示例为例,您的控制器操作应该像这样工作:

[HttpGet]
public async Task<IActionResult> ShowProblem()
{
    var heartbeats = await heartbeatService.GetLatest();
    logger.LogInformation("Issue reproduction", new { heartbeats });

    var currentUser = User.Identity.Name;

    return Ok(new { currentUser, heartbeats.Data });
}
于 2021-06-20T13:49:19.997 回答
-1

在 .NET Core 中,您无法直接从 HttpContext 检索用户身份。您还需要使用依赖注入来获取对 http 上下文实例的引用。

这一直对我有用:

public class IssueReproductionController : ControllerBase
{
    private readonly HeartbeatService heartbeatService;
    private readonly ILogger<IssueReproductionController> logger;
    private readonly string userName;

    private readonly HttpContext context;

    public IssueReproductionController(
        HeartbeatService heartbeatService,
        ILogger<IssueReproductionController> logger,
        IHttpContextAccessor httpContextAccessor)
    {
        this.heartbeatService = heartbeatService;
        this.logger = logger;
        this.context = httpContextAccessor.HttpContext;
    }

    [HttpGet]
    public async Task<IActionResult> ShowProblem()
    {
       ...
       var currentUser = this.context.Request.HttpContext.User.Identity.Name;
       ...
    }
    ...
于 2021-06-20T12:14:40.887 回答