Azure Cognitive ServiceのTranslator Text APIを利用して翻訳するサンプルコードです。
ほぼドキュメントのままです。
Azure側では、Translator Textリソースを作成して、Keysをコピーしておきます。
langには、翻訳後の言語を指定します。
翻訳前の言語は自動判定されます(クエリーで指定することもできます)。
どの言語がサポートされているかは以下のAPIで確認します。
https://docs.microsoft.com/ja-jp/azure/cognitive-services/translator/reference/v3-0-languages?tabs=curl
static string host = "https://api.cognitive.microsofttranslator.com";
static string subscriptionKey = "Keysの値";
public static async Task<string> Translate(string text, string lang)
{
string route = "/translate?api-version=3.0&to=" + lang;
System.Object[] body = new System.Object[] { new { Text = text } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// In the next few sections you'll add code to construct the request.
// Set the method to POST
request.Method = HttpMethod.Post;
// Construct the full URI
request.RequestUri = new Uri(host + route);
// Add the serialized JSON object to your request
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
// Add the authorization header
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
dynamic jarray = JsonConvert.DeserializeObject(jsonResponse);
foreach (var item in jarray[0]["translations"])
{
if (item["to"] == lang)
{
// Found
return item["text"];
}
}
// Not found
return text;
}
}