[英]User.Identity.Name is null in my ASP.NET Core Web API
[英]Why is `User.Identity.Name` `null` when running ASP.NET 6 project?
我正在開發一個為我們的客戶本地安裝的應用程序,因此我們只需要 Windows 身份驗證。 我目前正在將應用程序從 ASP.NET 4.8 更新到 ASP.NET 6。當我使用 IIS Express 啟動配置文件運行應用程序時,它按我預期的方式運行,但是當我使用“MyProject”啟動配置文件運行時, User.Identity.Name
是null
。
我的launchsettings.json
文件:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:42721"
}
},
"profiles": {
"MyProject": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "/",
"applicationUrl": "http://localhost:42721",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
我的Program.cs
文件:
using NLog;
using NLog.Web;
using System.Text.Json;
var logger = LogManager.Setup()
.LoadConfigurationFromAppSettings()
.GetCurrentClassLogger();
logger.Debug("init main");
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(60);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();
// Add services to the container.
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
app.MapControllers();
app.Run();
為什么 Windows 身份驗證在我使用 IIS Express 進行調試時有效,但在我使用“MyProject”啟動配置文件時卻無效?
以下行在您的 Program.cs 中很重要:
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate(); // which used by microsoft.aspnetcore.authentication.negotiate nuget package
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
//after app intialization:
app.UseAuthentication();
app.UseAuthorization();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.