你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:Azure AI 翻译 REST API

试用最新版本的 Azure AI 翻译。 在本快速入门中,开始使用翻译器服务以所选的编程语言或 REST API 翻译文本。 对于此项目,建议你在学习技术时使用免费定价层 (F0),在以后再升级到付费层进行生产。

先决条件

需要一个活动 Azure 订阅。 如果你没有 Azure 订阅,可以免费创建一个

  • 获得 Azure 订阅后,在 Azure 门户中创建一个翻译器资源

  • 部署资源后,选择“转到资源”并检索密钥和终结点。

    • 需要从资源获取密钥和终结点,以便将应用程序连接到翻译器服务。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。 可以在 Azure 门户的“密钥和终结点”页面上找到这些值:

      Screenshot: Azure portal keys and endpoint page.

      注意

      • 对于本快速入门,建议使用文本翻译单服务全局资源。
      • 使用单服务全局资源,你将在 REST API 请求中包含一个授权标头 (Ocp-Apim-Subscription-key)。 Ocp-Apim-Subscription-key 的值是文本翻译订阅的 Azure 密钥。
      • 如果选择使用 Azure AI 多服务或区域翻译资源,则需要两个身份验证标头(Ocp-Api-Subscription-KeyOcp-Api-Subscription-Region)。 Ocp-Apim-Subscription-Region 的值是与订阅关联的区域。
      • 有关如何使用 Ocp-Apim-Subscription-Region 标头的详细信息,请参阅文本翻译 REST API 标头

头文件

若要通过 REST API 调用翻译器服务,需要在每个请求中包含以下标头。 不用担心,我们会在每种编程语言的示例代码中为你包含标头。

有关翻译器身份验证选项的详细信息,请参阅翻译器 v3 参考指南。

标头 条件
Ocp-Apim-Subscription-Key Azure 门户中的翻译器服务密钥。 必需
Ocp-Apim-Subscription-Region 创建资源的区域。 •使用 Azure AI 多服务或区域(地理)资源(如美国西部)时为必需项
•·使用单服务全局翻译资源时为可选项
Content-Type 有效负载的内容类型。 接受的值为 application/json 或 charset=UTF-8。 必需
Content-Length 请求正文的长度。 可选

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

翻译文本

翻译器服务的核心操作是翻译文本。 在本快速入门中,你使用所选的编程语言生成一个请求,该请求采用单个源 (from) 并提供两个输出 (to)。 然后,我们将查看一些参数,这些参数可用于调整请求和响应。

有关 Azure AI 翻译服务请求限制的详细信息,请参阅文本翻译请求限制

设置 Visual Studio 项目

  1. 确保使用最新版本的 Visual Studio IDE

    提示

    如果你不熟悉 Visual Studio,请尝试学习 Visual Studio 简介 Learn 模块。

  2. 打开 Visual Studio。

  3. 在“开始”页上,选择“创建新项目”。

    Screenshot: Visual Studio start window.

  4. 在“创建新项目”页面上,在搜索框中输入“控制台” 。 选择“控制台应用程序”模板,然后选择“下一步” 。

    Screenshot: Visual Studio's create new project page.

  5. 在“配置新项目”对话框中,在项目名称框中输入 translator_quickstart。 将“将解决方案和项目置于同一目录中”复选框保持未选中状态,然后选择“下一步”。

    Screenshot: Visual Studio's configure new project dialog window.

  6. 在“其他信息”对话框窗口中,确保选择“.NET 6.0 (长期支持)”。 将“不使用顶级语句”复选框保持未选中状态,然后选择“创建”。

    Screenshot: Visual Studio's additional information dialog window.

使用 NuGet 安装 Newtonsoft.json 包

  1. 右键单击“translator_quickstart”项目并选择“管理 NuGet 包...”。

    Screenshot of the NuGet package search box.

  2. 选择“浏览”选项卡并键入“Newtonsoft.json”。

    Screenshot of the NuGet package install window.

  3. 若要将包添加到项目,请从右侧的包管理器窗口中选择“安装”。

    Screenshot of the NuGet package install button.

运行 C# 应用程序

注意

  • 从 .NET 6 开始,使用 console 模板的新项目将生成与以前版本不同的新程序样式。
  • 新的输出使用最新的 C# 功能,这些功能简化了你需要编写的代码。
  • 使用较新版本时,只需编写 Main 方法的主体。 无需包括顶级语句、全局 using 指令或隐式 using 指令。
  • 有关详细信息,请参阅新的 C# 模板生成顶级语句
  1. 打开 Program.cs 文件。

  2. 删除现有的代码,包括 Console.WriteLine("Hello World!") 行。 将代码示例复制并粘贴到应用程序的 Program.cs 文件中。 确保使用 Azure 门户翻译器实例中的值更新密钥变量:

using System.Text;
using Newtonsoft.Json;

class Program
{
    private static readonly string key = "<your-translator-key>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
    // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Input and output languages are defined as parameters.
        string route = "/translate?api-version=3.0&from=en&to=fr&to=zu";
        string textToTranslate = "I would really like to drive your car around the block a few times!";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

运行 C# 应用程序

将代码示例添加到应用程序后,选择 formRecognizer_quickstart 旁边的绿色“开始”按钮以生成和运行程序,或按 F5

Screenshot of the run program button in Visual Studio.

翻译输出:

成功调用后,应会看到以下响应:

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!",
                "to": "fr"
            },
            {
                "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!",
                "to": "zu"
            }
        ]
    }
]

后续步骤

完成了,恭喜! 你已了解如何使用翻译器服务翻译文本。

请浏览我们的操作指南文档并深入了解翻译服务的功能: