Microsoft Bot Framework Analytics API 调用不工作

Microsoft Bot Framework Analytics API call not working

我正在尝试创建一个翻译机器人,但当我发送消息时,机器人一直告诉我机器人代码有问题。目前,我只是想检测用户语言并将其打印在聊天中。 这是我写的代码:

    async Task DetectLanguage(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;
        string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";

        // create request to Text Analytics API
        HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
        detectLanguageWebRequest.Method = "POST";

        // create and send body of request
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string jsonText = serializer.Serialize(activity);

        string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
        byte[] data = Encoding.UTF8.GetBytes(body);
        detectLanguageWebRequest.ContentLength = data.Length;

        using (var requestStream = detectLanguageWebRequest.GetRequestStream())
            requestStream.Write(data, 0, data.Length);

        HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

        // read and and parse JSON response
        var responseStream = response.GetResponseStream();
        var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
        dynamic jsonResponse = serializer.DeserializeObject(jsonString);

        // fish out the detected language code
        var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
        if (languageInfo["score"] > (decimal)0.5)
            await context.PostAsync(languageInfo["iso6391Name"]);
        else
            await context.PostAsync("No language detected");

        context.Wait(DetectLanguage);
    }

当我尝试调试时,导致问题的行是这一行:

    HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

这是我在控制台中遇到的错误:

    iisexpress.exe Warning: 0 : Service url localhost:63556 is not trusted and JwtToken cannot be sent to it.

Exception thrown: 'System.Net.WebException' in mscorlib.dll

有人遇到过这个问题吗?

感谢转发的帮助:)

首先,关于您的实施的一些细节:

  • 我强烈建议使用 HttpClient 而不是 HttpWebRequest(您可以阅读为什么 here
  • 微软提供的API文档中有很好的实现TextAnalytics调用的示例(见this page末尾)
  • 另一种选择是使用 Nuget 包,如他们的文档 here 所示。请注意,在撰写此答案时它仍处于预发布阶段。

工作答案无需定义 类 对应于 API 中使用的对象:

private async Task DetectLanguage(IDialogContext context, IAwaitable<IMessageActivity> result)
{
    var msg = await result;
        
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "PUT YOU KEY HERE");

    // Request parameters
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString["numberOfLanguagesToDetect"] = "1";

    // HERE BE CAREFUL ABOUT THE REGION USED, IT MUST BE CONSISTENT WITH YOUR API KEY DECLARATION
    var uri = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/languages?" + queryString;

    // Request body
    var serializer = new JavaScriptSerializer();
    var body = "{ \"documents\": [ { \"id\": \"string\", \"text\": " + serializer.Serialize(msg.Text) + " } ]}";
    var byteData = Encoding.UTF8.GetBytes(body);
    var responseString = "";

    using (var content = new ByteArrayContent(byteData))
    {
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await client.PostAsync(uri, content);
        responseString = await response.Content.ReadAsStringAsync();
    }

    // fish out the detected language code
    dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
    var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
    var returnText = "No language detected";

    if (languageInfo["score"] > (decimal) 0.5)
    {
        returnText = languageInfo["iso6391Name"].ToString();
    }
    await context.PostAsync(returnText);

    context.Wait(DetectLanguage);
}