Microsoft Bot Framework Analytics API调用无法正常工作

问题描述 投票:1回答:1

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

    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.

抛出异常:mscorlib.dll中的“System.Net.WebException”

有人见过这个问题吗?

谢谢你的帮助:)

c# botframework azure-cognitive-services
1个回答
1
投票

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

  • 我强烈建议使用HttpClient而不是HttpWebRequest(你可以阅读为什么here
  • 您有很好的示例在Microsoft提供的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);
}
© www.soinside.com 2019 - 2024. All rights reserved.