Example of using ASP. NET5 REST APIs-creating your own online translation tools based on cloud platforms and cloud services

Source: Internet
Author: User

Example of using ASP. NET5 REST APIs-creating your own online translation tools based on cloud platforms and cloud services

As a programmer, he may be learning technology and new developments in the industry. When solving problems, he often needs to read English content. An English like me can only use translation tools to understand a rough idea; I can't help but feel that English is too important for learning computer knowledge! I recently found that IBM's cloud platform Blumemix provides language translation services and I feel good. I will study it. Here I will share my study process and how to use ASP. NET5 calls the rest api to create its own online translation tool and demonstrates how to publish it to the cloud platform so that everyone can access it through the network.

Application Effect display

 

A Bluemix account is a prerequisite for building a similar application, you do not have? Click here to register, there are already, click here to log on;

Basic understanding of HTML (Hypertext Markup Language;

Basic understanding of CSS (Cascading Style Sheets;

Basic understanding of JavaScript (a literal scripting language;

Basic understanding of ASP. NET5 programming;

A basic understanding of RESTful APIS;

I provide all the necessary code, but a basic understanding of these technologies helps you understand the details.

Step 1. Create your ASP. NET5 Application 1. Go to "dashboard" on the Bluemix user interface ". 2. Click Create application. 3. Click Web, select the entry template based on the guidance experience, specify the name, and select the encoding method. Enter the application name The Application name is unique. Next, use it as a second-level domain name to access your application! After clicking finish, wait for a while and then you can see the interface Then you can access the application you just created. For example: Step 2. To add a language translation service, click Add service or API on the application "Overview" in the Bluemix user interface to add the service to the application. You can also use the cf command line interface. See available options for processing applications. Select Language Translation in the service list. You can specify the service name or use the default one;

Obtain Service Information

Go to the application overview page, find the added service, and click "show creden”" to view the service details:

Access the service URL in a browser, for example:

Step 3. Prepare the development environment

For details about how to build the development environment, refer to the following article:

 
  1. // Call the background translation program functiondoExecTrans (){
  2. Vartxt = $ ("# InputText"). val (); if (txt = ""){
  3. Alert ("Enter the text to translate! "); Return;
  4. }
  5. $ ("# ProgressDiv"). show (); $. ajax ({
  6. Type: "GET", url: "/api/values/" + encodeURIComponent (txt ),
  7. DataType: "json ",
  8. Success: function (data) {$ ("# ProgressDiv"). hide ();
  9. Console. log (data); if (data. error ){
  10. Alert (data. error);} else {
  11. $ ("# OutputText"). text (data. text );}
  12. }, Error: function (data ){
  13. Console. log (data); ssss alert ("ErrorMsg:" + data );
  14. $ ("# ProgressDiv"). hide ();}
  15. });}

    Main background code: ValuesController. cs, interaction with Translation Service Web Service

    For the creation method, see ASP. NET5 Web API Controller Class learning.

    Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using System. net; using Microsoft. aspNet. mvc; using System. text; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink? LinkID = 397860 namespace dotnethelloworld. Controllers {[Route ("api/[controller]")] public class ValuesController: Controller {// GET: api/values [HttpGet] public IEnumerable
       
        
    Get () {return new string [] {"value1", "value2" };}// GET api/values/txt [HttpGet ("{txt}")] public async Task
        
         
    Get (string txt) {String retString = txt; try {// construct url, source is the language of the text to be translated, target specifies to translate why the language String uri = "https://gateway.watsonplatform.net/language-translation/api/v2/translate? "; Uri + =" source = en & target = es & text = "+ txt;
        
       
    System. net. http. httpClient httpClient = new System. net. http. httpClient (); // convert the service credential to the Base64 Encoding Format byte [] auth = Encoding. UTF8.GetBytes ("User name: Password"); // the user name and password String auth64 = Convert. toBase64String (auth); // create and specify the service credential. The authentication scheme is Basic httpClient. defaultRequestHeaders. authorization = new System. net. http. headers. authenticationHeaderValue ("Basic", auth64); retString = await httpClient. getStringAsync (uri); return "{\" text \ ": \" "+ retString +" \ "}";} catch (Exception ex) {return ex. message; // throw ex; }}// POST api/values [HttpPost] public void Post ([FromBody] string value) {} // PUT api/values/5 [HttpPut ("{id}")] public void Put (int id, [FromBody] string value) {}// DELETE api/values/5 [HttpDelete ("{id}")] public void Delete (int id ){}}}
    You may notice that the Code has two keywords: async and await ,. NET introduces async and await keywords (VB is Async and Await) to simplify the programming mode of asynchronous calls, which makes asynchronous calls easier.Step 5. Access Local running

    1. Save the modified File

    2. Press F5 or use the Debug menu

    Access

    After debugging is started, the browser window is automatically opened:

    Step 6. Upload the application

    Log on to Bluemix? You can use the cf push command to upload the application.

    Before you begin, you must: 1. Install the Cloud Foundry command line interface.

    Download the corresponding version based on your own operating system. I use a Windows 7 64-bit operating system, and do not need to install the Binaries version, Decompress the package directly to the Windows directory.. Click the dashboard "jstrans (name of the application you created)" to start encoding. You can view your own commands, for example: 2. Connect to Bluemix. Open the Command Prompt window: Start run, enter "cmd", Press enter to execute: cf api https://api.ng.bluemix.net, such as: 3, log on to Bluemix. Note: replace it with the command corresponding to your own account!
      cf login -u [email protected] -o [email protected] -s ivu4e   

    4. When issuing the cf push command, the cf command line interface provides a working directory for building and running the Bluemix environment of the application using buildpack.

    1. Enter the cf push command with the application name in the application directory. In the Bluemix environment, the application name must be unique. The following "-m 512 m" modifies the application memory quota. this parameter is optional, for example:Note: Before executing cf push, switch the current directory of the command line to the application directory you just created. For example
      C: \ nodejs \ net5trans \. Replace jstrans after cf push with the name of the application you created on Bluemix.Tip: when you use the cf push command, the cf command line interface copies all files and directories in the current directory to Bluemix. Make sure that the application directory contains only required files.

      The cf push command uploads the application and deploys it to Bluemix. For more information about cf push, see cf commands. For information about buildpack, see use the Community buildpack.

      If you have changed the application, you can run the cf push command again to upload the changes. The cf command line interface uses your previous options and your response to the prompt to update any running instances of the application through the new code segment. Tip: You can also upload or deploy applications from Bluemix DevOps Services. See use Web IDE in Node. js to develop Bluemix applications. Step 7. Perform a small test

      Go to the application page you just created through the dashboard, click Start code on the left side, and the top of the right side will show that your application is running.

      Click the link below to access the newly released application.

      Conclusion

      With IBM's Bluemix cloud platform, we can easily share our applications on the network;

      After a Web application is created, a second-level domain name is automatically obtained to access the application;

      The application running status in the Application overview can be used to conveniently view and manage the application running status;

      Here is a small example to show how to publish your application to the IBM Bluemix cloud platform,

      How to interact with the language translation service provided on the IBM cloud platform.

      If you have better applications or ideas, try sharing them with IBM's Bluemix cloud platform.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.