TLDR;我有几乎相同的控制器,它们仅通过使用async
/ await
(当然还有Task
)在本质上有所不同。非异步版本按预期返回当前用户的用户名,但async
等效版本不返回。
我想发现的是
- 这可能成立的情况
- 我可以使用这些工具(除了提琴手)来调查这个
注意:我无法针对 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 服务托管了这个。奇怪的行为似乎是不一致和不确定的。有时我看到我的用户名被退回,但我的同事在遇到有问题的端点时从来没有这样做过。