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

RestSharp调用Challonge API时GET正常但POST返回未授权如何解决

问题原因
  • Challonge v1 API 不识别JSON请求体中携带的api_key字段,仅接受查询参数(Query Parameter)或HTTP Basic Auth两种方式传递密钥
  • 你的POST请求中仅将api_key放入了JSON请求体(封装在Tournament对象中),同时注释了查询参数添加逻辑,导致服务端无法读取到密钥,返回401未授权
  • 额外注意:RestSharp中AddParameter方法默认的ParameterType.GetOrPost在POST请求携带JSON Body时,不会自动将参数追加到查询串,需要显式指定参数类型为QueryString
修复方案

方案1:显式添加查询参数传递api_key

改动最小,仅需调整POST请求的参数添加逻辑即可:

public string PostCall(string tournName, string key)
{
    client.AddDefaultHeader("Content-Type", "application/json");
    RestRequest request = new RestRequest("tournaments", DataFormat.Json);
    // 移除Tournament构造中的api_key传参,不需要在Body中携带密钥
    var obj = new Tournament(tournName);
    // 显式指定参数类型为QueryString,确保密钥追加到请求URL后
    request.AddParameter("api_key", key, ParameterType.QueryString);
    request.AddJsonBody(obj);
    IRestResponse response = client.Post(request);
    return response.StatusCode.ToString();
}

方案2:使用HTTP Basic Auth(更规范)

Challonge支持HTTP Basic认证规则,填写任意用户名、api_key作为密码即可,一次配置全局生效,不需要每个请求单独加密钥参数:

public class APICall
{
    HttpUtility http = new HttpUtility();
    RestClient client = new RestClient("https://api.challonge.com/v1/");
    
    public APICall()
    {
        // 全局配置Basic认证,用户名可任意填写,密码为你的api_key
        client.Authenticator = new HttpBasicAuthenticator("any_value", "your_api_key");
        client.AddDefaultHeader("Content-Type", "application/json");
    }

    public string GetCall()
    {
        RestRequest request = new RestRequest("tournaments", DataFormat.Json);
        // 不需要再单独传递api_key参数
        IRestResponse response = client.Get(request);
        return response.StatusCode.ToString();
    }

    public string PostCall(string tournName)
    {
        RestRequest request = new RestRequest("tournaments", DataFormat.Json);
        var obj = new Tournament(tournName);
        request.AddJsonBody(obj);
        IRestResponse response = client.Post(request);
        return response.StatusCode.ToString();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:54:05