[英]API Microsoft Translator Exception: “The data at the root level is invalid. Line 1, position 1.”
I am doing the migration of Microsoft Translation, from v2 to v3.我正在将微软翻译从 v2 迁移到 v3。 But I am getting the following exception:
但我收到以下异常:
There was an error deserializing the object of type System.String.
反序列化 System.String 类型的 object 时出错。 The data at the root level is invalid.
根级别的数据无效。 Line 1, position 1.
第 1 行,position 1。
(System.Runtime.Serialization.SerializationException)(System.Runtime.Serialization.SerializationException)
Inner exception: The data at the root level is invalid.
内部异常:根级别的数据无效。 Line 1, position 1.
第 1 行,position 1。
System.Exception {System.Xml.XmlException}System.Exception {System.Xml.XmlException}
This error happens on this line of code:此错误发生在这行代码上:
translation.Append((string)dcs.ReadObject(response));
Full method:完整方法:
public string TranslateText(string from, string to, string text)
{
var token = string.Empty;
try
{
retryPolicy.Execute(() =>
{
token = azureAuthentication.GetAccessToken();
});
var translation = new StringBuilder();
int charLength = Configuration.Configuration.CharLength;
List<string> lines = text.Split('.').Aggregate(new[] { "" }.ToList(), (a, x) =>
{
var last = a[a.Count - 1];
if ((last + x).Length > charLength)
{
a.Add(x);
}
else
{
a[a.Count - 1] = ($"{last}{x}.");
}
return a;
});
foreach (var str in lines)
{
string uri =$"https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation&textType={HttpUtility.UrlEncode(str)}&from=from_lang&to=to_lang";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", token);
try
{
retryPolicy.Execute(() =>
{
using (var response = httpWebRequest.GetResponse().GetResponseStream())
{
var dcs = new DataContractSerializer(Type.GetType("System.String"));
translation.Append((string)dcs.ReadObject(response));
}
});
}
catch (Exception ex)
{
throw new ExternalServiceUnavailableException(ex.Message, ex);
}
}
return translation.ToString();
}
catch(Exception ex)
{
throw new ExternalServiceUnavailableException(ex.Message, ex);
}
}
I have no idea why this error is occurring.我不知道为什么会发生此错误。 I looked out other questions regarding this error but I am not sure how to implement those resolutions here.
我查看了有关此错误的其他问题,但我不确定如何在此处实施这些解决方案。
Thank you谢谢
I think you're getting an error in your request so the deserialization is failing.我认为您的请求出现错误,因此反序列化失败。 I think this part
from=from_lang&to=to_lang
should be from={from_lang}&to={to_lang}
我认为这部分
from=from_lang&to=to_lang
应该是from={from_lang}&to={to_lang}
You're setting to the literal string from_lang, instead of a name of a valid language, like en or es.您正在设置文字字符串 from_lang,而不是有效语言的名称,如 en 或 es。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.