You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个启用Windows身份验证的.NET Core应用间发起基础API调用

.NET 6 Blazor Server调用Windows身份验证Web API报401的解决配置

问题场景

在内网环境使用Visual Studio 2022搭建两个.NET 6项目,实现Windows身份验证下的跨项目调用:

  • 创建TestFront:Blazor Server应用,身份验证类型为Windows,启用HTTPS
  • 创建TestApi:ASP.NET Core Web API,身份验证类型为Windows,启用HTTPS

TestApi的WeatherForecast接口可正常访问,但为新增的TrialController添加[Authorize]特性后,TestFront通过HttpClient调用https://localhost:44334/Trial/TrialGet时触发401未授权错误。

必要配置步骤

1. 让HttpClient传递Windows身份凭证

Blazor Server默认的HttpClient不会自动携带当前Windows用户的凭证,需在创建HttpClient时启用UseDefaultCredentials:

// 替换原有的HttpClient创建逻辑
var httpClientHandler = new HttpClientHandler
{
    UseDefaultCredentials = true // 关键:传递当前Windows用户凭证
};
using var httpClient = new HttpClient(httpClientHandler);
int i = await httpClient.GetFromJsonAsync<int>("https://localhost:44334/Trial/TrialGet");

注意:避免每次请求新建HttpClient,建议通过依赖注入注册Scoped或Singleton实例,防止套接字资源耗尽。

2. 为TestApi配置支持凭证的CORS策略

两个项目使用不同HTTPS端口属于跨域请求,需在TestApi中配置允许带凭证的CORS:

  1. 在Program.cs中添加CORS服务:
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowBlazorFront", policy =>
    {
        // 替换为你的TestFront的HTTPS地址
        policy.WithOrigins("https://localhost:xxxx")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 必须启用,允许传递身份凭证
    });
});
  1. 在中间件管道中启用CORS(需放在UseAuthorization之前):
app.UseCors("AllowBlazorFront");
app.UseAuthorization();

3. 确认TestApi的Windows身份验证配置

确保TestApi的Program.cs正确启用Windows身份验证:

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
    .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

同时检查launchSettings.json中Windows身份验证启用、匿名身份验证禁用:

"iisSettings": {
  "windowsAuthentication": true,
  "anonymousAuthentication": false,
  "iisExpress": {
    "applicationUrl": "https://localhost:44334",
    "sslPort": 44334
  }
}

4. 验证IIS Express的运行配置

确保两个项目都通过IIS Express以HTTPS运行,且launchSettings.json中的端口配置正确。对于localhost的跨域请求,浏览器默认允许凭证传递;若后续部署到正式内网服务器,需将站点添加到浏览器的可信站点列表中。

内容的提问来源于stack exchange,提问作者user8149311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:55:46