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

.NET Core 6 API通过Header传API Key时触发CORS错误求助

问题排查与解决方案

一、Header传递API Key时的CORS错误解决

浏览器发送含自定义Header(如apiKey)的跨域请求前,会自动发送OPTIONS预检请求,该请求不会携带自定义Header。你的ApiKeyMiddleware会拦截这个OPTIONS请求,因找不到apiKey Header直接返回401,导致浏览器判定预检失败,触发CORS错误。而Postman不会自动触发预检请求,所以能正常执行。

修复方式:修改ApiKeyMiddleware跳过OPTIONS请求验证

在InvokeAsync方法开头添加判断,让OPTIONS请求直接通过管道:

public async Task InvokeAsync(HttpContext context)
{
    // 跳过OPTIONS预检请求,交由CORS中间件处理
    if (context.Request.Method == HttpMethod.Options.Method)
    {
        await _next(context);
        return;
    }

    if (!context.Request.Headers.TryGetValue(APIKEY, out var extractedApiKey))
    {
        context.Response.StatusCode = 401;
        await context.Response.WriteAsync("Api Key was not provided ");
        return;
    }

    var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
    var apiKey = appSettings.GetValue<string>(APIKEY);

    if (!apiKey.Equals(extractedApiKey))
    {
        context.Response.StatusCode = 401;
        await context.Response.WriteAsync("Unauthorized client");
        return;
    }

    await _next(context);
}

二、Query String传递API Key时返回404但能获取结果的问题排查

可能原因及修复建议

  1. 路由匹配错误:
    检查前端请求URL是否完全匹配控制器路由api/Tests/{id},确认id参数为有效整数,无拼写或格式错误。

  2. 中间件管道顺序问题:
    当前ApiKeyMiddleware放在UseAuthorization之后,不符合API Key验证作为前置身份校验的逻辑,可能导致状态码异常。调整管道顺序:

    app.UseHttpsRedirection();
    app.UseCors("corsPolicy");
    // 将API Key验证移至认证授权前
    app.UseMiddleware<ApiKeyMiddleware>();
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.MapControllers();
    
  3. 响应状态码与内容不一致:
    在控制器中添加日志,确认返回的内容和状态码是否匹配:

    [HttpGet("{id}")]
    public async Task<ActionResult<Test>> GetTest(int id)
    {
        var test = await _context.Tests.FindAsync(id);
        if (test == null)
        {
            Console.WriteLine($"Test id {id} not found in database");
            return NotFound();
        }
        Console.WriteLine($"Returning test data for id {id}");
        return test;
    }
    

额外注意事项

  • 生产环境中,建议将AllowAnyOrigin改为指定允许的域名,避免安全风险。
  • API Key验证逻辑中,可将Header名称存入配置或常量,减少拼写错误概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:35:06