Simple creation and usage of. Net core webapi

Time:2020-5-23

preface

According to the current development trend of software development, webapi is used more and more widely, no matter front-end and back-end separation or providing data services, and. Net core is also the future development trend of our. Net developers, so it is necessary to learn to use. Net core API.

As a rookie of. Net, I am learning slowly and recording the steps I have learned step by step.

1、 Create project

Open vs2019 and create a new one ASP.NET Core web application.

Enter the project name and select the path to create.

Select. Net core. I’m using. Net core version 2.2. Select the API, and uncheck the one on the right.

The contents of the created project directory are as follows.

2、 Edit controller

Open the controllers folder, where I directly use the default created valuescontroller controller. (in fact, it’s because it’s an example. I’ve been lazy to rebuild it.)

The default content of valuescontroller controller is as follows. There are four HTTP methods, get, post, put and delete.

Rewrite the content of the controller and set the route to API / controller / method (API / [controller] / [action]). According to the two common requests of get and post, two get methods, one post method and one parameter class are written.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace FirstApi.Controllers
{
  //Routing settings
  [Route("api/[controller]/[action]")]
  [ApiController]
  public class ValuesController : ControllerBase
  {
    /// <summary>
    ///Get text
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ActionResult<string> Get()
    {
      return "Hello World!";
    }
    /// <summary>
    ///Add two numbers
    /// </summary>
    ///< param name = "num1" > first number < / param >
    ///< param name = "num2" > second number < / param >
    /// <returns></returns>
    [HttpGet]
    public ActionResult<int> Sum(int num1,int num2)
    {
      return num1 + num2;
    }
    /// <summary>
    ///Subtraction of two numbers
    /// </summary>
    ///< param name = "param" > parameter < / param >
    /// <returns></returns>
    [HttpPost]
    public ActionResult<int> Subtract(Param param)
    {
      int result = param.num1 - param.num2;
      return result;
    }
  }
  /// <summary>
  ///Parameters
  /// </summary>
  public class Param
  {
    /// <summary>
    ///First number
    /// </summary>
    public int num1 { get; set; }
    /// <summary>
    ///Second number
    /// </summary>
    public int num2 { get; set; }
  }
}

Then right click Project → property → debug, and the startup browser will point to the first get method by default.

Debug the run, access the first method, and return the result.

Visit the second method and add parameters to get the result.

The third method is post request, which can’t be input directly. It can be implemented in other ways.

3、 Build swagger

In this way, webapi is easy to implement, but it is not easy to manage. To better manage and test our interfaces, I use the swagger framework here.

What is swagger? Swagger is a standardized and complete framework for generating, describing, invoking, and visualizing restful style web services.

Right click the project and click Manage nuget packages.

Switch to browse, search“ Swashbuckle.AspNetCore ”, installation.

After installation, edit Startup.cs Documents.

Reference the following three namespaces.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace FirstApi.Controllers
{
  //Routing settings
  [Route("api/[controller]/[action]")]
  [ApiController]
  public class ValuesController : ControllerBase
  {
    /// <summary>
    ///Get text
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ActionResult<string> Get()
    {
      return "Hello World!";
    }
    /// <summary>
    ///Add two numbers
    /// </summary>
    ///< param name = "num1" > first number < / param >
    ///< param name = "num2" > second number < / param >
    /// <returns></returns>
    [HttpGet]
    public ActionResult<int> Sum(int num1,int num2)
    {
      return num1 + num2;
    }
    /// <summary>
    ///Subtraction of two numbers
    /// </summary>
    ///< param name = "param" > parameter < / param >
    /// <returns></returns>
    [HttpPost]
    public ActionResult<int> Subtract(Param param)
    {
      int result = param.num1 - param.num2;
      return result;
    }
  }
  /// <summary>
  ///Parameters
  /// </summary>
  public class Param
  {
    /// <summary>
    ///First number
    /// </summary>
    public int num1 { get; set; }
    /// <summary>
    ///Second number
    /// </summary>
    public int num2 { get; set; }
  }
}

Add the following code to the configureservices method, register the swagger generator, define a document, and set the comment path of the XML document,.

//Configure swagger
//Register the swagger generator and define a swagger document
services.AddSwaggerGen(c =>
{
  c.SwaggerDoc("v1", new Info
  {
    Version = "v1",
    Title = "interface document",
    Description = "RESTful API"
  });
  //Set XML document annotation path for swagger
  var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
  c.IncludeXmlComments(xmlPath);
});

Add the following code into the configure method, enable the middleware service to generate swagger and swaggerui, and set the routeprefix in swaggerui as an empty string, so that the root node( http://localhost : port) directly displays the swaggerui interface.

//Enable middleware services to generate swagger
app.UseSwagger();
//Enable middleware services to generate swaggerUI,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web App V1");
  c.RoutePrefix =  string.Empty ; // set root node access
});

After editing Startup.cs The complete code is as follows.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;

namespace FirstApi
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      //Configure swagger
      //Register the swagger generator and define a swagger document
      services.AddSwaggerGen(c =>
      {
        c.SwaggerDoc("v1", new Info
        {
          Version = "v1",
          Title = "interface document",
          Description = "RESTful API"
        });
        //Set XML document annotation path for swagger
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
      });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      //Enable middleware services to generate swagger
      app.UseSwagger();
      //Enable middleware services to generate swagger,指定Swagger JSON终结点
      app.UseSwaggerUI(c =>
      {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web App V1");
        c.RoutePrefix =  string.Empty ; // set root node access
      });
      app.UseMvc();
    }
  }
}

Then, right-click the item and click properties.

Choose build, choose our debug path.

Check the XML document file, fill it in automatically, and then a warning will appear (warning can be ignored for non obsessive compulsive disorder)

If you want to remove the warning, add 1591 shown above to the above undesired warning. Save it with Ctrl + s, and the warning will be gone.

Then click debug to remove the URL after launching the browser.

After that, run vs directly and you will enter the document UI page.

4、 Using swagger

Let’s open the first method and click the try it out button.

This is a method without parameters. Click execute to execute.

After execution, you can see the content returned by response body.

Click the second method, give two parameters, input the execution, and get the return result.

The parameter of the third method is model. To pass the JSON format, it has been generated by default. We just need to edit and change the value, and then execute it.

5、 Summary

Here is the end of the simple construction and use of. Net core API. This article learned how to create a. Net core API project and how to build a swagger to generate documents and use. Next, I will continue to learn and use. Net core API and record its process. I originally wanted to add a (1) to the title of this article, but I thought it might not be more recently. I’ll add it later. ㄟ( ▔, ▔ )ㄏ

Well, that’s all the content of this article. I hope that the content of this article has a certain reference learning value for your study or work. Thank you for your support for developpaer.