C# Microsoft Azure文本转换器-订阅密钥不工作
我正在尝试使用Microsoft Azure的文本转换器在控制台中构建一个基本的文本转换器。但是,我的订阅密钥根本不起作用。我已经多次生成它们,并且手动输入它们。请帮忙。我留下了钥匙以便进一步澄清。感谢您的阅读和帮助 代码生成此错误: if(null==subscriptionKey) { 抛出新异常(“请设置/导出环境变量:“+key\u var”)C# Microsoft Azure文本转换器-订阅密钥不工作,c#,azure,microsoft-cognitive,C#,Azure,Microsoft Cognitive,我正在尝试使用Microsoft Azure的文本转换器在控制台中构建一个基本的文本转换器。但是,我的订阅密钥根本不起作用。我已经多次生成它们,并且手动输入它们。请帮忙。我留下了钥匙以便进一步澄清。感谢您的阅读和帮助 代码生成此错误: if(null==subscriptionKey) { 抛出新异常(“请设置/导出环境变量:“+key\u var”) //此示例需要C#7.1或更高版本才能实现异步/等待。 使用制度; 使用System.Collections.Generic; 使用System
//此示例需要C#7.1或更高版本才能实现异步/等待。
使用制度;
使用System.Collections.Generic;
使用System.Net.Http;
使用系统文本;
使用System.Threading.Tasks;
//使用NuGet安装Newtonsoft.Json
使用Newtonsoft.Json;
名称空间TranslateExtSample
{
///
///表示翻译文本API返回的JSON的C#类。
///
公共类TranslationResult
{
公共检测语言检测语言{get;set;}
公共文本结果源文本{get;set;}
公共翻译[]翻译{get;set;}
}
公共类检测语言
{
公共字符串语言{get;set;}
公共浮动分数{get;set;}
}
公共类文本结果
{
公共字符串文本{get;set;}
公共字符串脚本{get;set;}
}
公共课翻译
{
公共字符串文本{get;set;}
公共文本结果音译{get;set;}
{get;set;}的公共字符串
公共对齐{get;set;}
公共句子长度SentLen{get;set;}
}
公共阶级联盟
{
公共字符串Proj{get;set;}
}
公共类句子长度
{
public int[]SrcSentLen{get;set;}
公共int[]TransSentLen{get;set;}
}
班级计划
{
private const string key_var=“b1f43a68dce24b0280360691ad68bc75”;
私有静态只读字符串subscriptionKey=Environment.GetEnvironmentVariable(key\u var);
私有常量字符串端点_var=”https://consoletexttranslator.cognitiveservices.azure.com/sts/v1.0/issuetoken";
私有静态只读字符串endpoint=Environment.GetEnvironmentVariable(endpoint_var);
静态程序()
{
if(null==subscriptionKey)
{
抛出新异常(“请设置/导出环境变量:“+key\u var”);
}
if(null==端点)
{
抛出新异常(“请设置/导出环境变量:”+endpoint_var);
}
}
//对转换器文本API的异步调用
静态公共异步任务TranslateTextRequest(字符串subscriptionKey、字符串端点、字符串路由、字符串inputText)
{
object[]body=new object[]{new{Text=inputText}};
var requestBody=JsonConvert.serialized对象(body);
使用(var client=new HttpClient())
使用(var request=new HttpRequestMessage())
{
//生成请求。
request.Method=HttpMethod.Post;
request.RequestUri=新Uri(端点+路由);
request.Content=newstringcontent(requestBody,Encoding.UTF8,“application/json”);
添加(“Ocp Apim订阅密钥”,subscriptionKey);
//发送请求并获得响应。
HttpResponseMessage response=await client.SendAsync(请求).ConfigureAwait(错误);
//将响应读取为字符串。
字符串结果=wait response.Content.ReadAsStringAsync();
TranslationResult[]反序列化输出=JsonConvert.DeserializeObject(结果);
//迭代反序列化的结果。
foreach(反序列化输出中的TranslationResult o)
{
//打印检测到的输入语言和置信度分数。
WriteLine(“检测到的输入语言:{0}\n可信度分数:{1}\n”,o.DetectedLanguage.language,o.DetectedLanguage.score);
//迭代结果并打印每个翻译。
foreach(o.Translations中的t翻译)
{
WriteLine(“翻译成{0}:{1}”,t.to,t.Text);
}
}
}
}
静态异步任务主(字符串[]args)
{
//这是我们的主要职能。
//输出语言在路由中定义。
//有关选项的完整列表,请参阅API参考。
// https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate
string route=“/translate?api version=3.0&to=de&to=it&to=ja&to=th”;
//提示您输入要翻译的文本。如果您愿意,可以
//提供一个字符串作为textToTranslate。
Console.Write(“键入您要翻译的短语?”);
string textToTranslate=“你好,汤米。”;
等待TranslateTextRequest(subscriptionKey、端点、路由、textToTranslate);
Console.WriteLine(“按任意键继续”);
Console.ReadKey();
}
}
}
请尝试下面的代码,它适合我:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;
namespace TranslateTextSample
{
/// <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; }
}
class Program
{
private const string subscriptionKey = "<your translator API key>";
private const string endpoint = "https://api.cognitive.microsofttranslator.com";
static Program()
{
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + subscriptionKey);
}
if (null == endpoint)
{
throw new Exception("Please set/export the environment variable: " + endpoint);
}
}
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
{
object[] body = new object[] { new { Text = inputText } };
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", subscriptionKey);
// 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();
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
// Print the detected input languge 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);
}
}
}
}
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.ReadKey();
Console.WriteLine("press anykey to exit");
}
static async Task MainAsync(string[] args)
{
string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
// Prompts you for text to translate. If you'd prefer, you can
// provide a string as textToTranslate.
string textToTranslate = "Hello, Tommy.";
await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;
namespace TranslateTextSample
{
/// <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; }
}
class Program
{
private const string subscriptionKey = "<your translator API key>";
private const string endpoint = "https://api.cognitive.microsofttranslator.com";
static Program()
{
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + subscriptionKey);
}
if (null == endpoint)
{
throw new Exception("Please set/export the environment variable: " + endpoint);
}
}
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
{
object[] body = new object[] { new { Text = inputText } };
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", subscriptionKey);
// 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();
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
// Print the detected input languge 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);
}
}
}
}
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.ReadKey();
Console.WriteLine("press anykey to exit");
}
static async Task MainAsync(string[] args)
{
string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
// Prompts you for text to translate. If you'd prefer, you can
// provide a string as textToTranslate.
string textToTranslate = "Hello, Tommy.";
await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
}
}
}