Skip to content

Latest commit

 

History

History
72 lines (49 loc) · 1.78 KB

translationeventing-csharp.md

File metadata and controls

72 lines (49 loc) · 1.78 KB

Create Translation Handler - C#

Create Translation Handler

Let's start with creating an empty ASP.NET Core app:

dotnet new web -o translation

Inside the translation/csharp folder, update Startup.cs to match with what we have.

Change the log level in appsettings.json to Information:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

Handle translation protocol

To encapsulate translation protocol, create a TranslationRequest.cs class.

Add Translation API

Add Translation API NuGet package to our project:

dotnet add package Google.Cloud.Translation.V2

Startup.cs extracts TranslationRequest out of the request.

var translationRequest = JsonConvert.DeserializeObject<TranslationRequest>(decodedData);

Once we have the translation request, we pass that to Translation API:

_logger.LogInformation("Calling Translation API");

var response = await TranslateText(translationRequest);
_logger.LogInformation($"Translated text: {response.TranslatedText}");
if (response.DetectedSourceLanguage != null)
{
    _logger.LogInformation($"Detected language: {response.DetectedSourceLanguage}");
}
await context.Response.WriteAsync(response.TranslatedText);

You can see the full code in Startup.cs.

Before building the Docker image, make sure the app has no compilation errors:

dotnet build

Create Dockerfile

Create a Dockerfile for the image.

What's Next?

Back to Integrate with Translation API