如何在自适应对话框的HttpRequest中添加身份验证令牌



我使用的是Botframework自适应对话框模板(c#(。我已经从一个HttpRequest获得了一个令牌,并将其保存为会话状态属性conversation.token,现在我正尝试使用此令牌使用HttpRequest进行另一个API调用。但从HttpRequest类的官方文档来看,似乎没有添加身份验证令牌的选项。我试图在Headers中添加令牌,但没有成功,它显示401未经授权错误。在自适应对话框的HttpRequest中应该如何处理授权?

new HttpRequest()
{
Url = "http://example.com/json",
ResultProperty = "conversation.httpResponse",
Method = HttpRequest.HttpMethod.GET,
ResponseType = HttpRequest.ResponseTypes.Json,
Headers = new Dictionary<string, AdaptiveExpressions.Properties.StringExpression>()
{
{"Authorization", "Bearer ${conversation.token.content.token}"},
},
},
new SendActivity("${conversation.httpResponse}"),

我没有使用HttpRequest,而是使用自定义代码在CodeAction中进行了API调用。首先发出POST请求以获取令牌,然后发出get请求以调用主API。在GET请求中,可以通过以下方式添加授权:client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

new CodeAction(async (dc, options) =>
{
var my_jsondata = new
{
Username = "username",
Password = "password"
};
var json = JsonConvert.SerializeObject(my_jsondata);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var Tokenurl = "https://example.com/token?HTTP/1.1";
using var Tokenclient = new HttpClient();
var Tokenresponse = await Tokenclient.PostAsync(Tokenurl, data);
string Toeknresult = Tokenresponse.Content.ReadAsStringAsync().Result;
var Tokenjo = JObject.Parse(Tokenresult);

using var client = new HttpClient();
var url = "https://example.com/mainapi?HTTP/1.1";
var accessToken = Tokenjo["token"];
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetAsync(url);
string result = response.Content.ReadAsStringAsync().Result;

dc.State.SetValue("conversation.httpresponse", response);
dc.State.SetValue("conversation.result", result);
return await dc.EndDialogAsync();
}),

相关内容

  • 没有找到相关文章

最新更新