Httpclient返回空的api密钥和客户端id密钥



好的,由于某种原因,第二双眼睛的时间我的属性总是返回null。

这里描述的密钥仅用于演示购买,在其他方面不起作用。

public class RoundTableAPIClient {
public string ApiKey { get; set; }
public string ClientSecret { get; set; }
}

这是一个我将所有API调用存储在中的类

private readonly HttpClient _httpClient;    
public RoundTableAPIClient() {
_httpClient = new HttpClient();
if (ApiKey != null | ClientSecret != null)  {
_httpClient.DefaultRequestHeaders.Add(Constants.ApiKey, ApiKey);
_httpClient.DefaultRequestHeaders.Add(Constants.ClientSecret, ClientSecret);
}
}

ApiKey和Client secret的值在我的库存控制器中为空,我正在中传递它们

public class StockController : Controller    {
private readonly IStringLocalizer<StockController> _localizer;
RoundTableAPIClient apiClient;
public StockController(IStringLocalizer<StockController> localizer)   {
_localizer = localizer;
apiClient = new RoundTableAPIClient();
}

这是我的get示例,我要去api获取这个函数包含在我的股票控制器中的数据。

public async Task<object> Get(DataSourceLoadOptions loadOptions) {
List<Stock> _result = new List<Stock>();
apiClient.DeveiceType = device.Desktop;
apiClient.DeveiceType = device.Desktop;
apiClient.ApiKey = "B538F53B-37F7-4564-B7C5-56AFF399252B";
apiClient.ClientSecret = "8132ED0B-8F0B-4841-8BF4-CE8438AC0F3E";        
_result =  await apiClient.GetStockFromApi();
return DataSourceLoader.Load(_result, loadOptions);
}
public async Task<List<Stock>> GetStockFromApi() {
List<Stock> _result = new List<Stock>();
var uri = new Uri(string.Format(ApiUrl + Constants.GetALlStock, string.Empty));
var response = await _httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode) {
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}

当我检查我的http客户端时,默认的头仍然是bank,我不明白为什么会这样。

编辑2

我应该这样做吗?

public async Task<List<Stock>> GetStockFromApi(string ApiKey,string ClientSecret) {
List<Stock> _result = new List<Stock>();
var uri = new Uri(string.Format(ApiUrl + Constants.GetALlStock, string.Empty));
var response = await _httpClient.GetAsync(uri);
if (ApiKey != null | ClientSecret != null) {
_httpClient.DefaultRequestHeaders.Add(Constants.ApiKey, ApiKey);
_httpClient.DefaultRequestHeaders.Add(Constants.ClientSecret, ClientSecret);
}
if (response.IsSuccessStatusCode)
{
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}

在构造函数中添加头的条件是ApiKey或ClientSecret不为null,但在该阶段它们将始终为null。您可能想要给出这些默认值,或者将它们作为参数添加到构造函数中。

最新更新