我试图通过ASP.NET函数调用MS Translator API,以翻译数据库中的各种字符串。
所有来自MS的示例都在C#中给出,所以我扔到转换器中去。 从我的搜索中,我很确定这是一个异步/等待问题。我也曾尝试在不同的时间将strString设置为不同的东西,但它会引发相同的错误,就像我没有正确等待一样。
在aspx页面上,我有这个:
<%# functions.translate(Eval("Description").ToString) %>
Description
是数据库中的一个字段,如果未传递到翻译功能,则可以正确显示。我还调用了其他功能来执行各种操作并正常工作。
在我的functions.vb中,我有:
Public Class TranslationResult
Public Property Translations As Translation()
End Class
Public Class Translation
Public Property Text As String
Public Property [To] As String
End Class
Public Class functions
Public Shared Async Function translate(strString As String) As Task(Of String)
Dim host As String = "https://api.cognitive.microsofttranslator.com"
Dim route As String = "/translate?api-version=3.0&to=fr"
Dim key As String = "0000000000000000000000000"
Dim body As Object() = New Object() {New With {Key .Text = strString}}
Dim requestBody = JsonConvert.SerializeObject(body)
Using client = New HttpClient()
Using request = New HttpRequestMessage()
request.Method = HttpMethod.Post
request.RequestUri = New Uri(host & route)
request.Content = New StringContent(requestBody, Encoding.UTF8, "application/json")
request.Headers.Add("Ocp-Apim-Subscription-Key", key)
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
Dim result As String = Await response.Content.ReadAsStringAsync()
Dim deserializedOutput As TranslationResult() = JsonConvert.DeserializeObject(Of TranslationResult())(result)
For Each o As TranslationResult In deserializedOutput
For Each t As Translation In o.Translations
strString = t.Text
Next
Next
End Using
End Using
Return strString
End Function
我遇到的错误是当我期望翻译后的字符串显示在System.Threading.Tasks.Task`1[System.String]
的网页上。
答案 0 :(得分:0)
我以您的代码为基础并使其正常运行。只需使用一个简单的Webform。
没有更改代码中的任何内容,但提示我添加
Imports System.Net.Http
通过Visual Studio 2019
vb.aspx背后的最终整个Web表单代码如下:
Imports System.Net.Http
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Public Class microsoftTranslator
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dim translatedText = functions.translate( "This is going to be one, two, three in french").Result
End Sub
Public Class TranslationResult
Public Property Translations As Translation()
End Class
Public Class Translation
Public Property Text As String
Public Property [To] As String
End Class
Public Class functions
Public Shared Async Function translate(strString As String) As Task(Of String)
Dim host As String = "https://api.cognitive.microsofttranslator.com"
Dim route As String = "/translate?api-version=3.0&to=fr"
Dim key As String = "0000000000000000000000000"
Dim body As Object() = New Object() {New With {Key .Text = strString}}
Dim requestBody = JsonConvert.SerializeObject(body)
Using client = New HttpClient()
Using request = New HttpRequestMessage()
request.Method = HttpMethod.Post
request.RequestUri = New Uri(host & route)
request.Content = New StringContent(requestBody, Encoding.UTF8, "application/json")
request.Headers.Add("Ocp-Apim-Subscription-Key", key)
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
Dim result As String = Await response.Content.ReadAsStringAsync()
Dim deserializedOutput As TranslationResult() = JsonConvert.DeserializeObject(Of TranslationResult())(result)
For Each o As TranslationResult In deserializedOutput
For Each t As Translation In o.Translations
strString = t.Text
Next
Next
End Using
End Using
Return strString
End Function
end class
End Class
要使其等待异步结果,请查看.result
属性
答案 1 :(得分:0)
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<!DOCTYPE html>
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim APIUrlToSend As String = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de"
Dim MyMainRequest As HttpWebRequest = CType(HttpWebRequest.Create(APIUrlToSend), HttpWebRequest)
MyMainRequest.Headers.Add("Ocp-Apim-Subscription-Key", "YOUR API CODE")
MyMainRequest.ContentType = "application/json; charset=utf-8"
MyMainRequest.Method = "POST"
' Send request
Dim MyJavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim TextToTranslate As String = MyJavaScriptSerializer.Serialize("Text to translate")
Dim MyMainRequestBody As String = "[{ Text: " & TextToTranslate & " }]"
Dim MyMainRequestBytesData As Byte() = Encoding.UTF8.GetBytes(MyMainRequestBody)
MyMainRequest.ContentLength = MyMainRequestBytesData.Length
Using RequestWriteStream = MyMainRequest.GetRequestStream()
RequestWriteStream.Write(MyMainRequestBytesData, 0, MyMainRequestBytesData.Length)
End Using
Dim MyFinalResponse As HttpWebResponse = MyMainRequest.GetResponse()
Dim MyFinalResponseStream As Stream = MyFinalResponse.GetResponseStream
Dim MyFinalResponseStreamReader As New StreamReader(MyFinalResponseStream, Encoding.GetEncoding("utf-8"))
Page.Response.Write(MyFinalResponseStreamReader.ReadToEnd())
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>