Advertisements

Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019


Introduction

There are more challenges we are facing for consuming a Web API because it contains  various methods such as GET,POST,PUT,DELETE. All these methods  contain various types of parameters like model,string,int,etc. Exactly we don’t know what property we need to pass in the model parameter and what are the relevant ones. These are the major challenges for a developer and so we need a proper documentation to solve this problem. That’s why we choose Swagger also known as OpenAPI and It  will provide all such benefits like interactive documentation, client SDK generation, and API discoverability. In this article we are explaining a lit bit basic configurations of Swagger in ASP.NET Core application. We can add more additional features on the Web API using swagger for that just read the reference document that we have mentioned in the Reference section.

We have tested the swagger documentation application in the latest VS 2019. So please check the following steps to kick start the initial process of installation.

1) Open Visual Studio 2019 and Click on “Create a new project”


2) Click on ASP.NET Core Web Application


3) Provision your new project and give the appropriate name and the location to be saved.


4) Choose API and Click on the Create button on the right side.


5) Open “Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution…” and click on Browse tab and search “Swashbuckle.AspNetCore” in the search bar and install it.

Model

We are going to create a Employee model for the demo purpose.

namespace SwaggerDocumentation.Model
{
    public class Employee
    {

        public int id { get; set; }
		
		public string Name { get; set; }
		
		public string Adress { get; set; }

		public string Department { get; set; }

    }
}

API Version Separation

In future if we are planning to release multiple versions of API, then, for the better readability purpose we can create a version folder for the API creation. This will help us to differentiate multiple versions in the API side and Swagger documentation. In the following screenshot we have created two folders one is “v1” ( Version 1 ) and another one is “v2” ( Version 2 ). obviously v2 will contain the latest version comparing to v1.

API Controller

We have created “EmployeeController” as the API controller in our application. Here we can see at the route level api path is set as “api/v1/[controller]” because when you hit the swagger it will first check the controller level then what will happen it will take two identical controller name as “Employee”. This will create ambiguous issue in the http request controller level, for that reason we have added two different request path for both versions v1 & v2.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SwaggerDocumentation.Model;

namespace SwaggerDocumentation.Controllers.v1
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        // GET: api/v1/Employee
        [HttpGet]
        public List<Employee> EmployeesDetails()
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees;
        }

        // GET: api/v1/Employee/5
        [HttpGet("{id}", Name = "Get")]
        public Employee EmployeeDetailsInformation(int id)
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   id = 1,
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   id = 2,
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   id = 3,
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees.Find(x => x.id == id);
        }

        // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

        // PUT: api/v1/Employee/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/v1/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

IControllerModelConvention

In the ASP.NET Core MVC we have application model and it will define convention abstractions that provide a simpler way to customize the behavior of the models without overriding the entire model. In simpler way we are modifying our app to follow different conventions from the default MVC behavior. The following method is clearly describing that it will take the last name of the “namespace” and it consider as the group name of the API Version. So in this case we can easily separate out versions when we  maintain multiple version of API’s in the application. The “GroupName”  can be declared as globally and locally, but in multiple API version case we can go with global scenario.

public class ApiExplorerVersionConvention : IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.v1"
            var apiVersion = controllerNamespace.Split('.').Last().ToLower();

            controller.ApiExplorer.GroupName = apiVersion;
        }
    }

The following way we can declare group name  locally but in this scenario you need to add the following decorator for each API method .

 // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

Middleware

We need to inject swagger service in the ASP.NET Core application using the middleware in startup class. Then only we can access the entire swagger service in our application.

ConfigureServices ( Inside the Startup.cs )

ConfigureServices method gets called by the runtime so we can use this method to register the services to the container  in the application. First of all we need to add “ApiExplorerVersionConvention” convention in the MVC service like the following way.

services.AddMvc(x => x.Conventions.Add(new ApiExplorerVersionConvention()));

The following code will register the swagger in our Application. There are many properties we use in the following code like “v1” & “v2” consider as GroupName , Title is displayed as “Swagger Documentation” and “Version 1.0” & “Version 2.0” is the version separation.

// Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Swagger Documentation", Version = "Version 1.0" });
                c.SwaggerDoc("v2", new Info { Title = "Swagger Documentation", Version = "Version 2.0" });
            });

Configure ( Inside the Startup.cs )

Configure method gets called by the runtime and use this method to configure the HTTP request pipeline. We are going to enable the generated Swagger as a JSON endpoint in the middleware and it will serve to the request.

app.UseSwagger();

The swagger UI and json endpoint we can mention in the following way.

app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
            });

launchSettings.json

In launchSettings.json we can setup swagger as the launch URL. This is not mandatory to give because for the demo purpose we have given launch URL as swagger. Otherwise In middleware we have SwaggerEndpoint  “/swagger/v1/swagger.json” so you can enter in the browser like “http://localhost:44392/api/swagger&#8221;.

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:62460",
      "sslPort": 44392
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SwaggerDocumentation": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

 

Output

Reference

Summary

From this article we have learned the Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019. I hope this article is useful for all the ASP.NET Web API beginners.

Advertisements

C# Corner Featured Community Leader 2019


 

Thanks a lot Mahesh Chand Sir making this wonder full video. Thank you for all the support C# Corner Team.

C-SharpCorner MVP Award 2019 🏆🏆🏆🏆


Everyday is a new beginning here in our C# Corner Community.We learn new things day by day and share the knowledge to the entire world. I as an individual had improved a lot in my technical aspects from this community. And thanks a lot for awarding me MVP for the fourth consecutive year. It is a great privilege to receive this award from the veterans. On this context I would like to thank my family and friends for staying with me during my ups and downs.

Thank you all !!

Congrats to all other MVP’s :  Q1 C# Corner MVP’s 2019

Getting Started With Angular Routing Using Angular CLI – Part Three


Introduction

In this article we are going to learn the basic routing concepts in Angular 6 using Angular CLI( Command Line Interface ). So before reading this article, you must read the following articles for more knowledge.

Routing in Application

In every application we do a minimal number of route concepts. For Eg While clicking the menu page it will redirect into child page or different page,etc. How can we do this in Angular ? Yes, There are few basic stuff we need to configure before the routing implementation in Angular.

Creating a Routing Module

By using command line parameter "--routing" we’re able to create a routing module in the Angular application. So by using any of the following command we can create routing module in Angular with the default routing setup. We have given “app-routing” as our routing module name.

ng generate module app-routing --flat --module=app
ng g m app-routing --flat --module=app

Note :

--flat puts the file in src/app instead of its own folder.
--module=app tells the CLI to register it in the imports array of the AppModule

The following code is generated after the above command execution.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: []
})
export class AppRoutingModule { }

Import Router in the Application

Angular Router is an optional service and it is not a part of "@angular/core" and Router Modules are the part of "@angular/router" library package.  So we need to import “RouterModule” and “Routes” from "@angular/router" library package.

import { RouterModule , Routes } from '@angular/router';

Add Routes

A very simple explanation in Angular docs is “Routes” tell the router which view to display when a user clicks a link or pastes a URL into the browser address bar. So the scenario is whether a click or paste a URL into the browser !!

const routes: Routes = [{}];

We have created a empty routes in our routing module, Now we need to add redirect page, default page , 404 page , etc. For this just type “a-path” inside the “{}” and It will display the possible routing options in the routing module.

Now we have added path and component name in the Routes.

const routes: Routes = [{ path: 'customer', component: CustomerComponent }];

We already know “app component” is our default launching  page in Angular application. So we need to setup a routing configuration in the app component.

RouterModule.forRoot()

We first initialize and import the router setup and it start listening the browser location changes.Whatever routes we have mentioned earlier will be injected into the forRoot().

@NgModule({
  exports: [RouterModule] ,
  imports: [
    CommonModule, [RouterModule.forRoot(routes)]
  ],
  declarations: []
})

RouterModule.forChild()

forChild() is used for the submodules and lazy loaded submodules as the following way.

@NgModule({
  exports: [RouterModule] ,
  imports: [
    CommonModule, [RouterModule.forChild(routes)]
  ],
  declarations: []
})

Router outlet

RouterOutlet  acts as a placeholder and it looks like a component. So when you place this outlet in an app component then it will be dynamically filled based on the current router state.

<router-outlet></router-outlet>

Navigation

The navigation we have added in the same app component page and while clicking on the “/customer” string content in “routerLink” then  It will redirect into the respective page. We can add more functionality in the anchor tag like active,binding array of links,etc

The Router Output

 

Page Not Found – 404 Error !!

If user is trying to access different page in the application and that is not part of the routing configuration then we need to display an Error message page called as Page Not Found. Any of the following command will create a “Page Not Found” page with using inline template.

ng generate component PageNotFound --inline-template
ng g c PageNotFound -t

We have modified the PageNotFound typescript file.

If you want to add bootstrap style in the application then import the following reference link in the style.css.

@import url('https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css');

We have updated the router URL as “PageNotFoundComponent” with path mentioned as “**” in the last route is a wildcard. if the requested URL doesn’t match any paths for routes defined in the following configuration. This will help us to displaying a “404 – Not Found” page or redirecting to another route.

const routes: Routes = [{ path: '', component: EmployeeComponent },
{ path: 'customer', component: CustomerComponent },
{ path: '**', component: PageNotFoundComponent }];

Output

Download :

Reference

Summary

From this article we have learned the basic routing concepts of  Angular CLI. I hope this article is useful for all the Angular CLI beginners.

Getting Started With Angular 6 Using Angular CLI – Part Two


Introduction

In this article we are going to learn the basic development commands in Angular CLI ( Command Line Interface ). So before reading this article, you must read our previous article Angular – Part One for more knowledge.

Angular CLI Version

We know recently Angular 7 is released but still we are using Angular 6 !  Yes, we have started the application before the release of Angular 7, may be upcoming years we can expect more number of updates from Angular Team. Using any of the following command we can identify the current Angular CLI version in the application.

ng --version
ng -v

The following output we can see the current Angular CLI version in the application.

Run the following command to identify the global version of Angular CLI.

npm list -global --depth 0

We realise that we are using the lower version of Angular CLI comparing to the global version. Before migrating to the higher version of Angular CLI,we need to understand the necessary updates.

Component

Components are the basic UI building block of an Angular application. We already created an angular basic application in our previous article and by default it contains  an app component and it’s respective files. So now we are going to create a component inside the application using any of the the following command. “customer” is our component name.

ng generate component customer
ng g c customer

Component is created successfully !! The customer component created inside the “app” folder.

Then how will you know which are the places we need to register the current generated component ? This is why we integrate a version control like “Git” in the application otherwise people blindly create the application without knowing anything. Then we will know exactly which are the places we need to register the component in the application like the following way.

Dry Run

If you are new to the Angular CLI and planning to create a component,module,class,etc in the application. Then the first time you will have some confusion for what name will give where this file will be created. For that we can use “dry run” command in Angular CLI, this command will stop the CLI from making any changes to the application or only display which are the files are going to create in the file system. We can use any of the following command to verify the dry run command.

ng generate component customer --dryRun
ng g c s -d

In the following screen shot at the end of the result it will mention the dry run “Note”.

Module

Module is a mechanism to group the components, pipes, services and directives that are related, in such a way that we can create an application. To define a module then we have to use the decorator “NgModule” in the typescript file for the following way.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CustomerComponent } from './customer/customer.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We can use any of  the following command to create a new module in the application.

ng generate module customer
ng g m customer

Class

Using any of the following command,we can create a class in the application.

ng generate class customer
ng g cl customer

In the above command we can see “cl” as the alias of class, but why they are not using “c”for class, because it is considered as “component”. Now the class will create under the “app” folder and but we include this as in the customer folder or any other folder. Then add the folder name at the front of the class name with slash “customer/”. Because we are planning to add the class inside the customer folder that is why we add slash after the folder.

ng generate class customer/customer

Interface

We are going to create a major contract in the application called as interface. We can run any of the following command to create an interface in the application.

ng generate interface customer
ng g i customer

Enum

We can run any of the following command to create an Enum in the application.

ng generate enum customer
ng g e customer

Inline Template and Style

As we know when we running the Angular component command it automatically generating all the respective files for the component. So how we can add separate Inline template or Inline Style or Css ? So run the following command to achieve both inline and style in the component.

Inline Template Command :

The following command will create a inline template instead of creating a separate html file in the system.

ng generate component employee --inline-template
ng g c employee -t

We can see that the typescript file  created an inline template instead of giving reference of the html file.

Inline Style Command :

The following command will create a inline style option instead of creating a separate css file in the system.

ng generate component student --inline-style
ng g c student -s

In the following typescript file, we can see it put as blank in the style reference area instead of referring the style css.

Download :

Reference

Summary

From this article we have learned the basic command of  Angular CLI. I hope this article is useful for all the Angular CLI beginners.

Getting started with Angular 6 using Angular CLI – Part 1


Introduction

Today we are going to learn most popular Single Page Application called as Angular Js using Angular CLI ( Command Line Interface ). We know by using Angular we can build modern applications such as web, mobile, or desktop in the real world. Previously we learnt about another famous single page application called as Aurelia.

Prerequisites

  • Download and Install : Node.Js ( Angular requires Node.js version 8.x or 10.x. )
  • Download and Install : VS Code ( A best opensource editor for developing Angular Application,etc ).
  • Download and Install : Git ( Not mandatory but use for a best practice ).

Angular CLI Installation

We can install Angular Command Line Interface after the installation of “node js” in our environment.  This will help you to create projects, generate application and library code, and perform such variety of ongoing development tasks such as testing, bundling, and deployment in our application. So this will reduce the time of development activities because of command line Interface register and generate files automatically at the beginning stage.  So that is why we need a version control for newly changed item in the application and it will identify  in which files what types of changes are reflected. This is more helpful for the beginners in   Angular CLI application development. Now we can install the Angular CLI globally by using the following command in our application.

npm install -g @angular/cli

Create a Project

Now we are going to create a simple project repository in our environment. The repository I have created in Github account and it is been cloned  in my environment(machine). The best practice of Angular CLI or any other application is configuring a version control in our VS Code otherwise we blindly create and check-in the code in project repository. No issues we can continue without configuring a version control in our application.

Go to our repository or  the place where we are planning to create a project setup , open the command prompt and run the following command.

ng new angular-app

Eg : “ng new [ProjectName]” our project name is a “angular-app”

Angular CLI created “angular-app” in our repository.

Install Angular Essential Extension

Click on Visual Studio Code Extension menu in left side bar then search “Angular Essential”  (john papa) in the search box. Once we install Angular Essential,  it will install all other supporting packages in the application automatically. Also It will generate a different icons for all the folders,ts files,style,json,etc.

Angular Build

We are generated a dummy application in our repository. The next step will be to build our application. For that open a “Command Terminal” in Visual Studio Code.

  1. Click on Visual Studio “Terminal” menu from the top of the menu list.
  2. “Terminal” menu displays a list of options ,  just click “New Terminal (  Cntrl + Shift + ~ )”.

There is one more short key for opening “Terminal” in VS Code ( “Cntrl + ~ ” ) . We can see the following terminal displayed on the right side bottom of  VS Code.

Now we need to build our application for that we need to open root directory of the application. May be when you open the Terminal in the VS code it will display the repository path of our application. So just change to application path by the following way.

The build artifacts will be stored in the dist/ directory folder in the application. Now run the Angular CLI build Command.

ng build

If you are getting the following error then that means we need to install “@angular-devkit/build-angular” dev dependency. This package is newly introduced in Angular 6.0.

The following command will help us to create devkit dependency in our application.

npm install --save-dev @angular-devkit/build-angular

If you are facing this same issue after the installation of dev kit then you need to uninstall and install the angular cli.

App Component

Components are the basic UI building block of an Angular app. So here we can see there is a “app” component generated under the “src -> app” folder in “angular-app” application. If you are using Angular CLI then it will auto generate all the files that are relevant for your basic application. For example in the following screen shot app folder contain such auto generated files are css,spec,ts and module.

Angular Serve

Now build is succeeded, Yes our application is ready to serve. Please run any of the following command ( one is alias or a short command ) to open our application in a browser.

ng serve --open
ng s -o

or If we don’t want to open application in a browser then just run the following command and navigate to "http://localhost:4200/".

ng serve

Bundling the application

So we can bundle our application using any of the following command and flag “–prod” bundle for production.

ng build --prod
ng serve --prod

for more options click here.

Changing the default port number

Every application should navigate to "http://localhost:4200/" as default. So If you are really thinking to open an application in a different port address then it is possible. Just run any of the following command.

ng s --port 3000 --open
ng s --port 3000 -o

Output :

As I mentioned earlier the default port we have changed to “3000” instead of “4200”.

Download :

Reference

Summary

From this article we have learned the basic configuration of Angular 6 using Angular CLI and few basic CLI commands. I hope this article is useful for all the Angular CLI beginners.

Cognitive Services : Convert Text to Speech in multiple languages using Asp.Net Core & C#


Introduction

In this article, we are going to learn how to convert text to speech in multiple languages using one of the important Cognitive Services API called Microsoft Text to Speech Service API ( One of the API in Speech API ). The Text to Speech (TTS) API of the Speech service converts input text into natural-sounding speech (also called as speech synthesis). It supports text in multiple languages  and gender based voice(male or female)

You can also refer the following articles on Cognitive Service.

Prerequisites

  1. Subscription key ( Azure Portal ) or Trail Subscription Key
  2. Visual Studio 2015 or 2017

Convert Text to Speech API

First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure Speech Service API in the Azure portal.
So please click on the “Create a resource” on the left top menu and search “Speech” in the search bar on the right side window or top of Azure Marketplace.

Now we can see there are few speech related “AI + Machine Learning ” categories listed in the search result.

Click on the “create” button to create Speech Service API.

Provision a Speech Service API ( Text to Speech ) Subscription Key

After clicking the “Create”, It will open another window. There we need to provide the basic information about Speech API.

Name : Name of the Translator Text API ( Eg. TextToSpeechApp ).

Subscription : We can select our Azure subscription for Speech API creation.

Location : We can select  location of resource group. The best thing is we can choose a location closest to our customer.

Pricing tier : Select an appropriate pricing tier for our requirement.

Resource group : We can create a new resource group or choose from an existing one ( We created a new resource group as “SpeechResource” ).

Now click on the “TextToSpeechApp” in dashboard page and it will redirect to the detailed page of TextToSpeechApp ( “Overview” ). Here, we can see the “Keys” ( Subscription key details ) menu in the left side panel. Then click on the “Keys” menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text to speech conversion using Microsoft Speech Service API.

Authentication

A token ( bearer ) based authentication is required in the Text To Speech conversion using Speech Service API. So we need to create an authentication token using “TextToSpeechApp” subscription keys. The following “endPoint” will help to create an authentication token for Text to speech conversion. The each access token is valid for 10 minutes and after that we need to create a new one for the next process.

https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken&#8221;

Speech Synthesis Markup Language ( SSML )

The Speech Synthesis Markup Language (SSML) is an XML-based markup language that provides a way to control the pronunciation and rhythm of text-to-speech. More about SSML ..

SSML Format :

<speak version='1.0' xml:lang='en-US'><voice xml:lang='ta-IN' xml:gender='Female' name='Microsoft Server Speech Text to Speech Voice (ta-IN, Valluvar)'>
        நன்றி
</voice></speak>

How to make a request

This is very simple process,  HTTP request is made in POST method. So that means we need to pass secure data in the request body and that will be a plain text or a SSML document. As per the documentation,it is clearly mentioned in most cases that we need to use SSML body as request. The maximum length of the HTTP request body is 1024 characters and the following is the endPoint for our http Post method.

https://westus.tts.speech.microsoft.com/cognitiveservices/v1&#8221;

The following are the HTTP headers required in the request body.

Pic source : https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-text-to-speech

Index.html

The following html contains the binding methodology that we have used in our application by using the  latest Tag helpers of ASP.Net Core.

Model

The following model contains the Speech Model information.

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.ComponentModel;

namespace TextToSpeechApp.Models
{
    public class SpeechModel
    {
        public string Content { get; set; }

        public string SubscriptionKey { get; set; } = "< Subscription Key >";

        [DisplayName("Language Selection :")]
        public string LanguageCode { get; set; } = "NA";

        public List<SelectListItem> LanguagePreference { get; set; } = new List<SelectListItem>
        {
        new SelectListItem { Value = "NA", Text = "-Select-" },
        new SelectListItem { Value = "en-US", Text = "English (United States)"  },
        new SelectListItem { Value = "en-IN", Text = "English (India)"  },
        new SelectListItem { Value = "ta-IN", Text = "Tamil (India)"  },
        new SelectListItem { Value = "hi-IN", Text = "Hindi (India)"  },
        new SelectListItem { Value = "te-IN", Text = "Telugu (India)"  }
        };
    }
}

Interface

The “ITextToSpeech” contains one signature for converting text to speech based on the given input. So we have injected this interface in the ASP.NET Core “Startup.cs” class as a “AddTransient”.

using System.Threading.Tasks;

namespace TextToSpeechApp.BusinessLayer.Interface
{
    public interface ITextToSpeech
    {
        Task<byte[]> TranslateText(string token, string key, string content, string lang);
    }
}

Text to Speech API Service

We can add the valid Speech API Subscription key and authentication token into the following code.

/// 

<summary>
        /// Translate text to speech
        /// </summary>


        /// <param name="token">Authentication token</param>
        /// <param name="key">Azure subscription key</param>
        /// <param name="content">Text content for speech</param>
        /// <param name="lang">Speech conversion language</param>
        /// <returns></returns>
        public async Task<byte[]> TranslateText(string token, string key, string content, string lang)
        {
            //Request url for the speech api.
            string uri = "https://westus.tts.speech.microsoft.com/cognitiveservices/v1";
            //Generate Speech Synthesis Markup Language (SSML) 
            var requestBody = this.GenerateSsml(lang, "Female", this.ServiceName(lang), content);

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(uri);
                request.Headers.Add("Ocp-Apim-Subscription-Key", key);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                request.Headers.Add("X-Microsoft-OutputFormat", "audio-16khz-64kbitrate-mono-mp3");
                request.Content = new StringContent(requestBody, Encoding.UTF8, "text/plain");
                request.Content.Headers.Remove("Content-Type");
                request.Content.Headers.Add("Content-Type", "application/ssml+xml");
                request.Headers.Add("User-Agent", "TexttoSpeech");
                var response = await client.SendAsync(request);
                var httpStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
                Stream receiveStream = httpStream;
                byte[] buffer = new byte[32768];

                using (Stream stream = httpStream)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] waveBytes = null;
                        int count = 0;
                        do
                        {
                            byte[] buf = new byte[1024];
                            count = stream.Read(buf, 0, 1024);
                            ms.Write(buf, 0, count);
                        } while (stream.CanRead && count > 0);

                        waveBytes = ms.ToArray();

                        return waveBytes;
                    }
                }
            }
        }

Download

Demo

Output

The given text is converted into speech in desired  language listed in a drop-down list using Microsoft Speech API.

Reference

See Also

You can download other source codes from MSDN Code, using the link, mentioned below.

Summary

From this article we have learned how to convert text to speech in multiple languages using Asp.Net Core & C# as per the API documentation using one of the important Cognitive Services API ( Text to Speech API is a part of Speech API ). I hope this article is useful for all Azure Cognitive Services API beginners.

%d bloggers like this: