从Azure机器人调用WebAPI

时间:2017-03-09 14:38:07

标签: c# azure asp.net-web-api bots botframework

我是Azure Bot编程(C#)的新手,无法找到关于此主题的好文章。

我想让用户使用Bot“订阅”邮件列表。我构建了一个Form对话框和Form Flow。它会询问用户的电子邮件地址。

我需要做的是将其发布到外部WebAPI(json)并获得响应并处理响应。

有人可以给我一些关于如何从Bot调用WebAPI的指示吗?

    public async Task Subscribe(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
    {
        context.Call(SubscribeForm.BuildFormDialog(FormOptions.PromptInStart), SubscribeFormComplete);
    }

    private async Task SubscribeFormComplete(IDialogContext context, IAwaitable<SubscribeForm> result)
    {
        try
        {
            var form = await result;
            if (form != null)
            {
                await context.PostAsync("Thanks for subscribing! You can always remove yourself by typing unsubscribe.");
            }
            else
            {
                await context.PostAsync("Form returned empty response!");
            }
        }
        catch (OperationCanceledException)
        {
            await context.PostAsync("I am sorry you decided not to subscribe! If you change your mind just type 'subscribe' again.");
        }

        context.Wait(this.MessageReceived);
    }


        [Serializable]
public class SubscribeForm
{
    [Prompt("What is your email address?")]
    [Required()]
    [DataType(DataType.EmailAddress)]
    public string EmailAddress { get; set; }

    public static IForm<SubscribeForm> BuildForm()
    {
        // Builds an IForm<T> based on BasicForm
        return new FormBuilder<SubscribeForm>()
            .Message("We often send out updates on new features. We don't spam.  You can type 'quit' to cancel this.")
           .Build();
    }

    public static IFormDialog<SubscribeForm> BuildFormDialog(FormOptions options = FormOptions.PromptInStart)
    {
        // Generated a new FormDialog<T> based on IForm<BasicForm>
        return FormDialog.FromForm(BuildForm, options);
    }
}

1 个答案:

答案 0 :(得分:2)

这是我如何调用Microsoft的Cognitive服务LUIS的示例,我在静态类上有方法,并且该方法是异步的。

方法:

 public static class CognitiveHelper
    {
        private const string UrlLuis = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/a267a797-9584-41a5-83f3-xxxxxxxxx?subscription-key=xxxxxxxxxxxxxxxxxxxxxxx&q=";
    public static async Task<LuisObjects> GetLuisAnswer(string textToEvaluate)
            {
                if (string.IsNullOrWhiteSpace(textToEvaluate)) throw new ArgumentException("Null argument");

                textToEvaluate= HttpUtility.UrlEncode(textToEvaluate);
                var urlLuisWithRequest = UrlLuis + textToEvaluate;

                var client = new HttpClient();
                var body = new { };

                var serializedBody = new JavaScriptSerializer().Serialize(body);
                byte[] bodyByte = Encoding.UTF8.GetBytes(serializedBody );

                using (var content = new ByteArrayContent(bodyByte))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var response= await client.GetAsync(urlLuisWithRequest );
                    var responseContent= await respuesta.Content.ReadAsStringAsync();

                    var javaScriptSerializer = new JavaScriptSerializer();
                    var resultTextAnalysis= javaScriptSerializer.Deserialize<LuisResult>(responseContent);
                    return new LuisObjects()
                    {
                        Entities= resultTextAnalysis.entities.ToList(),
                        TopScoringIntent = resultTextAnalysis.topScoringIntent
                    };
                }
            }
}

呼叫:

  var luisResponse = await CognitiveHelper.GetLuisAnswer(activity.Text);