gpt4 book ai didi

c# - Asp.Net Core 2.1 Windows 身份验证。 HttpContext.User.Identity.Name 在 IIS 中不起作用

转载 作者:太空狗 更新时间:2023-10-29 23:53:19 26 4
gpt4 key购买 nike

环境:

Windows 10IIS 10/Visual Studio 2017 Community w/IIS Express已安装 Windows 身份验证安全功能启用 Windows 身份验证 & 启用基本身份验证 & 禁用匿名身份验证

我有一个 Asp.Net Core 2.1 项目,这个项目将在 Intranet 中运行。所以我需要 Windows 身份验证。

启动:

 public class Startup
{
private IConfigurationRoot _appSettings;
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
_appSettings = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();

}

private IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(8640); //Sessions Time
});
services.AddDistributedMemoryCache();

services.AddDbContext<PMContext>();
services.AddSingleton<IConfigurationRoot>(_appSettings);
PMContext.ConnectionString = _appSettings.GetConnectionString("DefaultConnection");
services.AddAuthentication(IISDefaults.AuthenticationScheme);

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHangfireServer();
app.UseHttpsRedirection();
app.UseSession();
app.UseStaticFiles();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Intro}/{action=Index}/{id?}");
});

}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseAuthentication();
app.Run(async (context) =>
{
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
UserName = context?.User?.Identity?.Name
}));
});

//在我的家庭 Controller 中;

var UserComputerName = contextAccessor.HttpContext.User.Identity.Name;

这段代码在我的本地主机上工作,但在 IIS 服务器上不工作:/我尝试解决了同样的错误,但我无法解决。

最佳答案

确保您已在 IIS 中禁用匿名身份验证。接下来,如果您调用 User.Identity.Name ,您将在 Controller 中获取用户详细信息,如果您使用 Windows 身份验证,则无需注入(inject) HttpContextAccessor。

关于c# - Asp.Net Core 2.1 Windows 身份验证。 HttpContext.User.Identity.Name 在 IIS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51821277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com