我为我正在开发的 Bot App 创建了一个接口来使用 Refit 调用 Prestashop API。为了调用 API,您需要使用我拥有的 Prestashop API 密钥进行身份验证。要使用浏览器进行查询,我只需要使用以下格式调用 url:
$"https://{ApiKey}@{mypage}.com/api"
@
它使用签名前指定的 Api Key 进行身份验证。要定义改装,HttpClient
我在 Startup.cs 中使用此代码:
// This is the ApiUrl from the appsettings.json file
var apiUrl = Configuration.GetSection("PrestashopSettings").GetSection("ApiUrl").Value;
// We add the Api and specify the de/serialization will be XML
services.AddRefitClient<IPrestashopApi>(
new RefitSettings
{
ContentSerializer = new XmlContentSerializer()
})
.ConfigureHttpClient(c => c.BaseAddress = new System.Uri(apiUrl));
然后我将 API 注入我的一个类并调用它的一个函数。URL 似乎是正确的,如果我将完整的 URL(基础 + [Get] url)粘贴到浏览器,它会正确返回 XML。但是当我从应用程序中执行此操作时,它会返回一个异常:
Microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter:Error: Exception caught : Refit.ApiException: Response status code does not indicate success: 401 (Unauthorized).
at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in D:\a\1\s\Refit\RequestBuilderImplementation.cs:line 274
--- End of stack trace from previous location where exception was thrown ---
使用 Refit 的 HttpClient 进行身份验证的正确方法是什么?难道我做错了什么?
更新:
所以我尝试了这个:
public class HttpAuthentication : HttpClientHandler
{
private readonly string Token;
public HttpAuthentication(string token)
{
Token = token ?? throw new ArgumentException(nameof(token));
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = Token;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
这段代码在我的Startup.cs
:
var apiKey = Configuration.GetSection("PrestashopSettings").GetSection("ApiKey").Value;
var storeUrl = Configuration.GetSection("PrestashopSettings").GetSection("StoreUrl").Value;
// We add the Api and specify the de/serialization will be XML, and we specify the Authentication Client.
services.AddRefitClient<IPrestashopApi>(
new RefitSettings
{
ContentSerializer = new XmlContentSerializer()
})
.ConfigureHttpClient((c) => c.BaseAddress = new System.Uri(storeUrl))
.ConfigureHttpMessageHandlerBuilder((c) => new HttpAuthentication(apiKey));
而且我仍然收到相同的错误消息。