快速入门:使用 C# 通过文本翻译 API 来翻译字符串Quickstart: Use the Translator Text API to translate a string using C#

本快速入门介绍如何使用 .NET Core、C# 7.1 或更高版本以及文本翻译 REST API 将英语文本字符串翻译为德语、意大利语、日语和泰语。In this quickstart, you'll learn how to translate a text string from English to German, Italian, Japanese and Thai using .NET Core, C# 7.1 or later, and the Translator Text REST API.

此快速入门需要包含文本翻译资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator Text resource. 如果没有帐户,可以使用试用帐户获取订阅密钥。If you don't have an account, you can use the trial to get a subscription key.

Tip

如果你想一次看到所有代码,这个示例的源代码可以在 GitHub 上找到。If you'd like to see all the code at once, the source code for this sample is available on GitHub.

先决条件Prerequisites

创建 .NET Core 项目Create a .NET Core project

打开新的命令提示符(或终端会话)并运行以下命令:Open a new command prompt (or terminal session) and run these commands:

dotnet new console -o translate-sample
cd translate-sample

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 translate-sample 的目录。It creates a new .NET console application, and creates a directory named translate-sample. 第二个目录转到项目的目录。The second command changes to the directory for your project.

接下来需安装 Json.Net。Next, you'll need to install Json.Net. 在项目的目录中,运行以下命令:From your project's directory, run:

dotnet add package Newtonsoft.Json --version 11.0.2

选择 C# 语言版本Select the C# language version

本快速入门需要 C# 7.1 或更高版本。This quickstart requires C# 7.1 or later. 可以通过多种方式来更改项目的 C# 版本。There are a few ways to change the C# version for your project. 本指南将介绍如何调整 translate-sample.csproj 文件。In this guide, we'll show you how to adjust the translate-sample.csproj file. 如需所有可用选项,例如在 Visual Studio 中更改语言的选项,请参阅选择 C# 语言版本For all available options, such as changing the language in Visual Studio, see Select the C# language version.

打开项目,然后打开 translate-sample.csprojOpen your project, then open translate-sample.csproj. 确保将 LangVersion 设置为 7.1 或更高版本。Make sure that LangVersion is set to 7.1 or later. 如果没有用于语言版本的属性组,请添加以下行:If there isn't a property group for the language version, add these lines:

<PropertyGroup>
   <LangVersion>7.1</LangVersion>
</PropertyGroup>

将所需命名空间添加到项目Add required namespaces to your project

此前运行的 dotnet new console 命令创建了一个项目(包括 Program.cs)。The dotnet new console command that you ran earlier created a project, including Program.cs. 此文件是需放置应用程序代码的位置。This file is where you'll put your application code. 打开 Program.cs,替换现有的 using 语句。Open Program.cs, and replace the existing using statements. 这些语句可确保你有权访问生成并运行示例应用所需的所有类型。These statements ensure that you have access to all the types required to build and run the sample app.

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;

为 JSON 响应创建类Create classes for the JSON response

接下来,我们将创建一组在反序列化由文本翻译 API 返回的 JSON 响应时使用的类。Next, we're going to create a set of classes that are used when deserializing the JSON response returned by the Translator Text API.

/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class TranslationResult
{
    public DetectedLanguage DetectedLanguage { get; set; }
    public TextResult SourceText { get; set; }
    public Translation[] Translations { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public float Score { get; set; }
}

public class TextResult
{
    public string Text { get; set; }
    public string Script { get; set; }
}

public class Translation
{
    public string Text { get; set; }
    public TextResult Transliteration { get; set; }
    public string To { get; set; }
    public Alignment Alignment { get; set; }
    public SentenceLength SentLen { get; set; }
}

public class Alignment
{
    public string Proj { get; set; }
}

public class SentenceLength
{
    public int[] SrcSentLen { get; set; }
    public int[] TransSentLen { get; set; }
}

创建文本翻译函数Create a function to translate text

Program 类中,创建一个名为 TranslateTextRequest() 的异步函数。Within the Program class, create an asynchronous function called TranslateTextRequest(). 此函数采用四个参数:subscriptionKeyhostrouteinputTextThis function takes four arguments: subscriptionKey, host, route, and inputText.

// This sample requires C# 7.1 or later for async/await.
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string host, string route, string inputText)
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

序列化翻译请求Serialize the translation request

接下来需创建 JSON 对象并将其序列化,其中包含要翻译的文本。Next, we need to create and serialize the JSON object that includes the text you want to translate. 请记住,可以在 body 中传递多个对象。Keep in mind, you can pass more than one object in the body.

object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);

实例化客户端并发出请求Instantiate the client and make a request

以下行实例化 HttpClientHttpRequestMessageThese lines instantiate the HttpClient and the HttpRequestMessage:

using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
  // In the next few sections you'll add code to construct the request.
}

构造请求并输出响应Construct the request and print the response

HttpRequestMessage 中,需执行以下操作:Inside the HttpRequestMessage you'll:

  • 声明 HTTP 方法Declare the HTTP method
  • 构造请求 URIConstruct the request URI
  • 插入请求正文(序列化的 JSON 对象)Insert the request body (serialized JSON object)
  • 添加必需的标头Add required headers
  • 发出异步请求Make an asynchronous request
  • 使用之前创建的类输出响应Print the response using the classes you created earlier

HttpRequestMessage 添加以下代码:Add this code to the HttpRequestMessage:

// Build the request.
// Set the method to Post.
request.Method = HttpMethod.Post;
// Construct the URI and add headers.
request.RequestUri = new Uri(host + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", "your region");

// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
// Deserialize the response using the classes created earlier.
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
    // Print the detected input language and confidence score.
    Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
    // Iterate over the results and print each translation.
    foreach (Translation t in o.Translations)
    {
        Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
    }
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 Ocp-Apim-Subscription-RegionIf you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. 详细了解如何使用多服务订阅进行身份验证Learn more about authenticating with the multi-service subscription.

将其放在一起Put it all together

最后一步是在 Main 函数中调用 TranslateTextRequest()The last step is to call TranslateTextRequest() in the Main function. 在此示例中,我们将翻译为德语 (de)、意大利语 (it)、日语 (ja) 和泰语 (th)。In this sample, we're translating to German (de), Italian (it), Japanese (ja), and Thai (th). 找到 static void Main(string[] args) 并将其替换为以下代码:Locate static void Main(string[] args) and replace it with this code:

static async Task Main(string[] args)
{
    // This is our main function.
    // Output languages are defined in the route.
    // For a complete list of options, see API reference.
    // /cognitive-services/translator/reference/v3-0-translate
    string host = "https://api.translator.azure.cn";
    string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
    string subscriptionKey = "YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE";
    // Prompts you for text to translate. If you'd prefer, you can
    // provide a string as textToTranslate.
    Console.Write("Type the phrase you'd like to translate? ");
    string textToTranslate = Console.ReadLine();
    await TranslateTextRequest(subscriptionKey, host, route, textToTranslate);
}

你会注意到,在 Main 中声明了 subscriptionKeyhostrouteYou'll notice that in Main, you're declaring subscriptionKey, host, and route. 此外,你将使用 Console.Readline() 提示用户输入并将值分配给 textToTranslateAdditionally, you're prompting the user for input with Console.Readline() and assigning the value to textToTranslate.

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到项目目录,然后运行以下命令:From the command line (or terminal session), navigate to your project directory and run:

dotnet run

示例响应Sample response

运行示例后,应当会看到输出到终端的以下内容:After you run the sample, you should see the following printed to terminal:

Detected input language: en
Confidence score: 1

Translated to de: Hallo Welt!
Translated to it: Salve, mondo!
Translated to ja: ハローワールド!
Translated to th: หวัดดีชาวโลก!

此消息是从原始 JSON 构建的,如下所示:This message is built from the raw JSON, which will look like this:

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Hallo Welt!",
        "to": "de"
      },
      {
        "text": "Salve, mondo!",
        "to": "it"
      },
      {
        "text": "ハローワールド!",
        "to": "ja"
      },
      {
        "text": "หวัดดีชาวโลก!",
        "to": "th"
      }
    ]
  }
]

清理资源Clean up resources

请务必删除示例应用的源代码中的机密信息,例如订阅密钥。Make sure to remove any confidential information from your sample app's source code, like subscription keys.

后续步骤Next steps

查看 API 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

另请参阅See also