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

.NET 6 MVC/控制台请求Web API时Authorization Header为null,Postman正常

问题分析与解决方案

核心问题

你的.NET 6 API在Postman请求时能正常获取Authorization头,但MVC/控制台应用通过HttpClient调用时,API端获取到的Authorization头为null。主要可能是HTTPS重定向导致头丢失、API缺少JWT认证服务配置或请求配置问题。

解决方案

1. 修复HTTPS重定向的头丢失问题

你的API启用了UseHttpsRedirection,如果MVC使用HTTP地址(如http://localhost:5031)调用,会触发302重定向到HTTPS。默认情况下,HttpClient在跨协议重定向时不会携带Authorization头,导致API无法接收。

解决办法二选一:

  • 直接使用HTTPS地址调用:将MVC中的client.BaseAddress改为API的HTTPS地址,例如:
    client.BaseAddress = new Uri("https://localhost:xxxx/api/"); // 替换为你的API HTTPS端口
    
  • 配置HttpClient允许重定向并携带凭据:
    using (HttpClient client = new HttpClient(new HttpClientHandler 
    { 
        AllowAutoRedirect = true, 
        UseDefaultCredentials = true 
    }))
    {
        // 原有代码不变
    }
    

2. 为API添加JWT认证服务配置

你的API Program.cs仅启用了app.UseAuthentication(),但未在服务注册阶段配置JWT认证逻辑,这会导致认证中间件无法正确处理JWT头,甚至可能过滤掉头信息。

在var app = builder.Build();之前添加以下代码:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

// ... 其他服务注册代码 ...

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        var key = Encoding.UTF8.GetBytes("gdyegwuhqd9387ejnfkqk210998plnxbuqqoowsaxlKohxpqud87654hjcyg");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "GShop-WEB-API-10072023-001",
            ValidAudience = "GShop-WEB-API-10072023-001",
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ClockSkew = TimeSpan.Zero
        };
    });

3. 排查请求头格式与完整性

  • 确认MVC中"Bearer " + token的格式正确,Bearer后有且仅有一个空格,token无截断或多余字符。
  • 在API的GetAllUsers方法中打印完整请求头,验证MVC发送的请求是否真的包含Authorization头:
    var allHeaders = string.Join("\n", Request.Headers.Select(h => $"{h.Key}: {string.Join(", ", h.Value)}"));
    Console.WriteLine(allHeaders);
    

4. 前端AJAX场景的CORS配置(若适用)

如果你的MVC是通过前端页面(如Razor View的AJAX)调用API,而非服务器端HttpClient,需配置CORS允许自定义头:

  1. 在API服务注册阶段添加CORS配置:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin", policy =>
        {
            policy.WithOrigins("http://localhost:你的MVC端口")
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
    
  2. 取消API Program.cs中//app.UseCors("AllowSpecificOrigin");的注释,确保它在UseRouting()之后、UseAuthentication()之前:
    app.UseRouting();
    app.UseCors("AllowSpecificOrigin");
    app.UseAuthentication();
    app.UseAuthorization();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:34:54