使用ASP.NETCore时,为什么HttpContext.User.Identity.Name对于等效于工作同步控制器的异步控制器显示为空?
c#
TLDR;我有几乎相同的控制器,它们仅通过使用async/ await(当然还有Task)而存在实质性差异。非异步版本按预期返回当前用户的用户名,但async等效版本不会。
我想发现的是
- 这可能适用的情况
- 我可以使用这些工具(除了 Fiddler)来调查这个
注意:我无法针对 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;
}
}
}
启动文件
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 服务托管了这个。奇怪的行为似乎是不一致和不确定的。有时我会看到我的用户名被返回,但我的同事在遇到有问题的端点时从未这样做过。
回答
您不应尝试在控制器构造函数中访问特定于 HttpContext 的数据。该框架不保证何时构造构造函数,因此很可能在IHttpContextAccessor可以访问当前HttpContext. 相反,您应该仅在您的控制器操作本身内访问特定于上下文的数据,因为它保证作为请求的一部分运行。
使用 时IHttpContextAcccessor,您应该始终HttpContext仅在需要查看上下文的那一刻访问它。否则,您很可能正在使用过时的状态,这会导致各种问题。
但是,在使用控制器时,您实际上根本不需要使用IHttpContextAccessor。相反,框架将为您提供多个属性,以便您可以直接在控制器上访问 HttpContext 甚至用户主体(在 Razor 页面和 Razor 视图中,有类似的属性可供使用):
ControllerBase.HttpContextControllerBase.UserControllerBase.RequestControllerBase.Response
请注意,这些属性仅在控制器操作中可用,而在构造函数中不可用。有关更多详细信息,请参阅此相关帖子。
以您的示例为例,您的控制器操作应该像这样工作:
[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 });
}