我正在尝试创建一个翻译机器人但是当我发送消息时,机器人一直告诉我机器人代码有问题。目前,我只是想检测用户语言并在聊天中打印出来。 这是我写过的代码:
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.
抛出异常:&#39; System.Net.WebException&#39;在mscorlib.dll中
有人见过这个问题吗?
感谢您的帮助:)
答案 0 :(得分:1)
首先,有关您的实施的一些细节:
HttpClient
代替HttpWebRequest
(您可以阅读原因here)TextAnalytics
调用的良好示例(请参阅this page末尾)无需定义与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);
}