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

使用StrawberryShake初始化GraphQL客户端遇405错误及手动配置问题

解决Sonar GraphQL端点下StrawberryShake的配置问题

一、搞定dotnet graphql init的405错误

Sonar的GraphQL API只支持POST请求,但dotnet graphql init默认用GET拉取Schema,所以这个命令直接用不了。得手动获取Schema:

  • 用curl发送POST请求获取完整Schema:
    curl -X POST https://sonar.software/你的GraphQL端点路径 \
    -H "Authorization: Bearer 你的Sonar令牌" \
    -H "Content-Type: application/json" \
    -d '{"query": "{ __schema { types { name fields { name type { name kind ofType { name kind } } } } } }"}'
    
  • 把返回结果里data.__schema的内容提取出来,保存为项目根目录下的schema.graphql文件。

二、修复代码自动生成失败问题

按以下步骤逐一排查配置:

  1. 检查NuGet包是否安装正确
    确保已安装以下包(版本建议与你使用的StrawberryShake.Tools保持一致):

    • StrawberryShake.Transport.Http
    • StrawberryShake.CodeGeneration.CSharp
  2. 配置graphqlrc.json
    确保配置文件参数正确,参考示例:

    {
      "schema": "schema.graphql",
      "documents": "**/*.graphql",
      "extensions": {
        "strawberryShake": {
          "name": "SonarGraphQLClient",
          "namespace": "你的项目命名空间",
          "output": "Generated/GraphQL",
          "transport": {
            "type": "http",
            "url": "https://sonar.software/你的GraphQL端点路径"
          },
          "dependencyInjection": true
        }
      }
    }
    
  3. 设置GraphQL文件的生成操作
    右键query.graphql文件 → 属性 → 生成操作,选择GraphQL Compile。

  4. 手动触发代码生成
    打开终端进入项目目录,执行命令:

    dotnet graphql generate
    

    若存在语法错误,可先执行dotnet graphql validate排查问题。

  5. 配置认证信息
    在项目的依赖注入配置文件(如Program.cs)中添加Bearer认证:

    using System.Net.Http.Headers;
    
    builder.Services.AddSonarGraphQLClient()
        .ConfigureHttpClient(client =>
        {
            client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", "你的Sonar令牌");
        });
    

三、验证配置

执行项目构建,检查Generated目录下是否生成了对应的C#客户端代码,之后即可通过依赖注入使用SonarGraphQLClient执行查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:20:15