从具有托管身份的Web应用调用Azure翻译服务

juzqafwq  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(125)

我是Azure新手。我正在从Web应用程序调用Azure翻译服务p。我想使用托管身份,到目前为止我尝试了以下方法。**您认为这是正确的方法吗?或者我还需要在Web应用程序身份中执行任何操作吗?**x1c 0d1x
1.在翻译服务中启用托管身份
1.在Azure中授予对翻译服务的访问权限翻译=>访问控制(IAM)=>添加角色分配=>创建托管身份的贡献者。

  1. Web应用程序中的代码集成
    //初始化Azure翻译客户端
    var credential = new ChainedTokenCredential(new ManagedIdentityCredential(),new AzureCliCredential()); var translatorClient = new TranslationClient(new Uri(endpoint),credential);
64jmpszr

64jmpszr1#

我同意Nicolas R的观点。每当你想将Web应用连接到任何资源时,最好将Web应用管理的身份连接到翻译服务,然后通过Azure Web应用中间件或代码访问翻译API。
请参考此MS Q & A answer流程以在Angular应用程序中使用认知服务。使用相同的步骤为您的C# .net Web应用程序,由Sedat SALMAN撰写。

为您的Web应用启用托管身份,如下所示:-

x1c 0d1x的数据

授予此 * 托管身份访问翻译服务的权限,如下所示:-



现在将此C# Translator服务代码集成到您的Web应用中间件中,以返回翻译API。您也可以从Web应用调用此Rest API。参考如下:-
添加一个类TranslationService.cs,并添加以下代码,其中包含正确的API键、位置和翻译服务的端点,如下所示:-

不带托管标识的TranslationService.cs


using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class TranslationService
{
    private static readonly string key = "xxxxxxc051dfbc";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    
    private static readonly string location = "australiaeast";

    public static async Task TranslateText(Stream body)
    {
       
        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[] requestBody1 = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            
            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);
           
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            
            HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
           
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

字符串

具有托管身份的TranslationService.cs您可以根据您的用例使用任何一个代码:-

using Azure.Identity;
using Azure.Core;
using Azure.AI.Translation.Document;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public class TranslationService
{
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    public static async Task<string> TranslateText()
    {
        string textToTranslate = "I would really like to drive your car around the block a few times!";

        var tokenCredential = new ManagedIdentityCredential();
        var translationClient = new DocumentTranslationClient(new Uri(endpoint), tokenCredential);

        var options = new TranslationRequestOptions { FromLanguage = "en", ToLanguages = { "fr", "zu" } };
        var documents = new List<DocumentTranslationInput>
        {
            new DocumentTranslationInput("1", textToTranslate),
        };

        var operation = await translationClient.StartTranslationAsync(documents, options);

        // Wait for the translation operation to complete
        await operation.WaitForCompletionAsync();

        if (operation.GetRawResponse().Status == 200)
        {
            var result = operation.GetValues().FirstOrDefault()?.Translations.FirstOrDefault()?.Text;
            return result ?? "Translation failed.";
        }
        else
        {
            return "Translation failed.";
        }
    }
}


在Asp.net Web应用程序的页面中的共享文件夹中创建一个Razor页面:-

翻译.cshtml:-

@page
@model TranslationModel

<button id="translateButton" class="btn btn-primary">Translate</button>

@section scripts {
    <script>
        document.getElementById('translateButton').addEventListener('click', function () {
            // Call the translation function when the button is clicked
            fetchTranslation();
        });

        function fetchTranslation() {
            fetch('/Translation/Translate')
                .then(response => response.text())
                .then(result => {
                    console.log(result);
                    // You can display the translation result as needed on the page.
                })
                .catch(error => {
                    console.error('Translation error:', error);
                });
        }
    </script>
}

翻译.cshtml.cs:-

using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Threading.Tasks;

public class TranslationModel : PageModel
{
    public async Task OnGet()
    {
        // This is the default handler when the page is requested. You can leave it empty or add any necessary initialization code.
    }
}

更新Program.cs如下:-

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// Map your translation route
app.MapGet("/Translation/Translate", async context =>
{
    // Call the TranslateText method from the TranslationService
    await TranslationService.TranslateText(context.Response.Body);
});

app.MapRazorPages();

app.Run();


对托管Identity Web应用程序应用相同的逻辑。

输出:-


相关问题