我为正在开发的Bot应用程序创建了一个接口,用于使用Refit调用Prestashop API。 为了调用该API,您需要使用我拥有的Prestashop API密钥进行身份验证。要使用浏览器查询,我只需要调用以下格式的网址:
$"https://{ApiKey}@{mypage}.com/api"
它使用@
符号前指定的Api密钥进行身份验证。要定义改装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));
我仍然收到相同的错误消息。