从Botframework向Azure测试WebChat发送消息

时间:2019-07-25 08:45:33

标签: c# azure post botframework bots

我当前正在尝试从Bot Framework仿真器向Azure中的测试Web聊天发送消息。我的问题是尝试此操作时:

var my2Response = await myClient.SendAsync(request).ConfigureAwait(false);

我得到StatusCode: 403, ReasonPhrase: 'Forbidden',,但我不知道该怎么办。我注意到request.Content也有标头,并尝试了以下疯狂的操作:request.Content.Headers.Add("Authorization", "Bearer " + myToken);

但是您可能会猜到,这不是解决方案。如何通过Botframework将帖子发送到Azure测试Webchat? (如果可行,我想尝试通过MS Teams向测试网络聊天发送消息)

这是相关代码:

           HttpClient myClient = new HttpClient();
            myClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var myToken = token;
            myClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", myToken);

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new System.Uri("https://webchat.botframework.com/v3/conversations/conversationID/activities"),
                Content = new StringContent("{\"type\": \"message\", \"text\": \"I come from teams\", \"from\": {\"id\": \"bot@somthing\", \"name\": \"teams\"}}", System.Text.Encoding.UTF8),

            };
            request.Content.Headers.ContentType.MediaType = "application/json";
            request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Add("Authorization", "Bearer " + myToken);
            var my2Response = await myClient.SendAsync(request).ConfigureAwait(false);
            my2Response.EnsureSuccessStatusCode();
            var myResponseBody = await my2Response.Content.ReadAsStringAsync().ConfigureAwait(false);

编辑

我正在使用的令牌是从这里生成的:https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token

1 个答案:

答案 0 :(得分:0)

更改了我的代码,现在可以使用了:

            HttpClient myClient = new HttpClient();
            myClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var myToken = token;
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://webchat.botframework.com/v3/conversations/ConversationID/activities"))
            {
                requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", myToken);
                requestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": \"I come from teams\", \"from\": {\"id\": \"bot@someID\", \"name\": \"teams\"}}", System.Text.Encoding.UTF8, "application/json");
                var myResponse = await myClient.SendAsync(requestMessage);
            }