快速入门:使用 C# 通过文本翻译 API 获取受支持语言的列表Quickstart: Use the Translator Text API to get a list of supported languages using C#

在本快速入门中,请使用文本翻译 API 获取翻译、音译和字典查找支持的语言列表。In this quickstart, you get a list of languages supported for translation, transliteration, and dictionary lookup using the Translator Text API.

提示

如果你想一次看到所有代码,这个示例的源代码可以在 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 languages-sample
cd languages-sample

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 languages-sample 的目录。It creates a new .NET console application, and creates a directory named languages-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

将所需命名空间添加到项目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 Newtonsoft.Json;

创建获取语言列表的函数Create a function to get a list of languages

Program 类中创建名为 GetLanguages 的函数。Within the Program class, create a function called GetLanguages. 该类封装用于调用 Languages 资源的代码,并将结果输出到控制台。This class encapsulates the code used to call the Languages resource and prints the result to console.

static void GetLanguages()
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

设置主机名和路径Set the host name, and path

将以下行添加到 GetLanguages 函数。Add these lines to the GetLanguages function.

string host = "https://api.translator.azure.cn";
string route = "/languages?api-version=3.0";

实例化客户端并发出请求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
  • 添加必需的标头Add required headers
  • 发出异步请求Make an asynchronous request
  • 输出响应Print the response

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

// Set the method to GET
request.Method = HttpMethod.Get;
// Construct the full URI
request.RequestUri = new Uri(host + route);
// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
// Pretty print the response
Console.WriteLine(PrettyPrint(jsonResponse));
Console.WriteLine("Press any key to continue.");

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 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.

要使用“Pretty Print”(响应格式)打印响应,请将此函数添加到 Program 类:To print the response with "Pretty Print" (formatting for the response), add this function to your Program class:

static string PrettyPrint(string s)
{
    return JsonConvert.SerializeObject(JsonConvert.DeserializeObject(s), Formatting.Indented);
}

将其放在一起Put it all together

最后一步是在 Main 函数中调用 GetLanguages()The last step is to call GetLanguages() in the Main function. 找到 static void Main(string[] args) 并添加以下行:Locate static void Main(string[] args) and add these lines:

GetLanguages();
Console.ReadLine();

运行示例应用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

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

清理资源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