You need to enable JavaScript to run this app. 使用RestSharp调用API返回Unauthorized问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用RestSharp调用API返回Unauthorized问题求助

问题:RestSharp调用内部API返回Unauthorized,Postman可正常运行

我正尝试使用RestSharp调用公司内部API接口,在Postman中先生成JWT令牌,再将令牌作为查询参数传入受保护接口可正常返回数据,但用RestSharp复现流程时始终返回Unauthorized错误。


获取JWT令牌的代码

public async Task<string> GetAuthorizationToken(CancellationToken token)
{
  var options = new RestClientOptions(_baseUrl);
  using var client = new RestClient(options);

  var request = new RestRequest(_resource)
    .AddParameter("client_id", _clientId)
    .AddParameter("client_secret", _clientSecret)
    .AddParameter("grant_type", _grantType)
    .AddParameter("password", _password)
    .AddParameter("username", _username);
  var response = await client.PostAsync<TokenResponseDto>(request);
  return response.Access_Token;
        
}

调用受保护接口的代码

public async Task<CustomerResponseDto> GetCustomerDetailsByAccountNumber(CustomerRequestDto accountDetails, CancellationToken token)
{
    var acccestoken = await GetAuthorizationToken(token);
    Console.WriteLine(acccestoken);
    accountDetails.AccountType = _acct_type;
    var options = new RestClientOptions(_baseUrl);
    using var client = new RestClient(options);
    var request = new RestRequest(_customer_resource)
        .AddParameter("access_token", acccestoken)
        .AddHeader("Content-Type", "application/json")
        .AddHeader("Accept", "application/json")
        .AddJsonBody(accountDetails);
    var response = await client.PostAsync<CustomerResponseDto>(request);

    return response;
}

Postman正常调用的URL示例

http://x.x.x.x:{port}/{service}/secured/{customer_resource}?access_token={auth_token}


补充信息

  • 类构造函数:
public CustomerRespository(string clientId, string acctstmresource, string customer_resource, string clientSecret, string grantType, string password, string username, string baseUrl, string resource, string baseUrl2, string correlationId, string xclient, string resource2, string bankcode, string acct_type)
{
    _clientId = clientId;
    _clientSecret = clientSecret;
    _grantType = grantType;
    _password = password;
    _username = username;
    _baseUrl = baseUrl;
    _resource = resource;
    _baseUrl2 = baseUrl2;
    _correlationId = correlationId;
    _xclient = xclient;
    _resource2 = resource2;
    _bankcode = bankcode;
    _acctstmresource = acctstmresource;
    _customer_resource = customer_resource;
    _acct_type = acct_type;

}
  • 已确认JWT令牌可正常生成

报错信息

Request Failed with status Unauthorized

堆栈跟踪

at RestSharp.RestClientExtensions.<PostAsync>d__16`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CCMP.Persistence.Repositories.CustomerRespository.<GetCustomerDetailsByAccountNumber>d__17.MoveNext() in E:\source\repos\CCMP-API\CCMP.Persistence\Repositories\CustomerRespository.cs:line 83
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CCMP.Application.Services.CustomerService.<GetCustomer>d__3.MoveNext() in E:\source\repos\CCMP-API\CCMP.Application\Services\CustomerService.cs:line 27

问题排查与解决

核心问题是AddParameter的默认行为:对于POST请求,RestSharp会默认将参数添加到请求体中,但你的API要求access_token作为查询参数放在URL里(与Postman调用方式一致)。

修改调用受保护接口的代码,明确指定参数类型为查询参数即可:

var request = new RestRequest(_customer_resource)
    // 明确指定参数类型为QueryString,确保access_token出现在URL中
    .AddParameter("access_token", acccestoken, ParameterType.QueryString)
    .AddHeader("Content-Type", "application/json")
    .AddHeader("Accept", "application/json")
    .AddJsonBody(accountDetails);

额外优化建议

  1. 复用RestClient:RestClient是线程安全的,无需每次请求都创建新实例,可提升性能。
  2. 验证URL拼接:检查_baseUrl与_customer_resource的拼接结果是否和Postman中的一致,可通过RestSharp日志查看最终请求URL。
  3. 核对请求体:确认accountDetails序列化后的JSON与Postman中发送的请求体完全一致,避免因请求体格式问题导致权限验证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:10:33