.Net Core WebApi simple to create and use

  According to the current development trend of software development, both before and after the end of the separation or provide data services, more and more widely used WebApi, but also our .NET Core .NET developers in the future development trend, so that learn to use .NET Core Api It is very necessary.

  .NET himself as a rookie, is slowly learning, will learn step by step recorded.

First, create a project

  Open VS2019, create a new ASP.NET Core Web applications.

  Enter a project name, select the path created.

  Select .NET Core me here is .NET Core 2.2 version, select the API, to select the right to cancel.

  Create a project directory as follows.

Second, the editing controller

  Open the Controllers folder, and here I directly ValuesController controller created by default. (In fact, because this is an example I lazy to build a (¯.¯))

  ValuesController default controller as follows. There are four HTTP methods, respectively, Get, Post, Put and Delete.

  The contents of the controller to re-write it, will set the route for api / controller / method ( api / [the Controller] / [Action] ). Post according to conventional and two Get request, a write method and a Post Get two methods, a parameter class.

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

namespace FirstApi.Controllers
{
    //路由设置
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        /// <summary>
        /// 获取文本
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<String > the Get () 
        { 
            return  " the Hello World! " ; 
        } 
        ///  <Summary> 
        /// adding two numbers
         ///  </ Summary> 
        ///  <param name = "num1"> first number < / param> 
        ///  <param name = "num2"> second number </ param> 
        ///  <Returns> </ Returns> 
        [HttpGet]
         public ActionResult < int > the Sum ( int num1, int num2) 
        { 
            return + num1 num2;
        }
        /// <summary>
        /// 两数相减
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<int> Subtract(Param param)
        {
            int result = param.num1 - param.num2;
            return result;
        }
    }
    /// <summary>
    /// 参数
    /// </summary>
    public class Param
    {
        /// <summary>
        ///first number
        /// </summary>
        public int num1 { get; set; }
        /// <summary>
        /// 第二个数
        /// </summary>
        public int num2 { get; set; }
    }
}

  Then right → Properties → Project commissioning, will launch the default browser for the first point to Get method.

  Commissioning, access to the first method, results are returned.

  The second access method add parameters to obtain results.

  The third method is Post request can not be directly input can be achieved in other ways.

Third, build Swagger

  Such WebApi is simple to achieve, but this is not easy to manage. In order to better manage and test our interface, I've used the Swagger Framework.

  What Swagger that? Swagger is a standardized and complete framework for generating, description, and visualization calls for RESTful Web services.

  Right project, click Manage NuGet package.

  Switch to the browser, search for " Swashbuckle.AspNetCore ", installation.

  After the installation is complete, edit Startup.cs file.

  Refers to the following three namespaces.

using System.IO;
using System.Reflection;
using Swashbuckle.AspNetCore.Swagger;

  Was added ConfigureServices method in the following code, register Swagger generator, defining a document path provided xml document annotation.

// Configure Swagger
 // Register Swagger generator, defining a document Swagger 
services.AddSwaggerGen (C => 
{ 
    c.SwaggerDoc ( " V1 " , new new Info 
    { 
        Version = " V1 " , 
        the Title = " interface document " , 
        the Description = " the API a RESTful " 
    }); 
    // set xml document annotation path Swagger 
    var xmlFile $ = " {Assembly.GetExecutingAssembly () GetName ()} .xml the Name.. " ;
     var XMLPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

  Join in the Configure method in the following code to enable the use of middleware services and generate Swagger SwaggerUI, the SwaggerUI the RoutePrefix set to an empty string, so that we can root node (http: // localhost: port) displayed directly SwaggerUI interface.

// Enable middleware services generated Swagger 
app.UseSwagger ();
 // enable generation middleware services SwaggerUI, designated Swagger JSON endpoint 
app.UseSwaggerUI (C => 
{ 
    c.SwaggerEndpoint ( " /swagger/v1/swagger.json " , " the Web Vl the App " ); 
    c.RoutePrefix = String .Empty; // set the root access 
});

  After editing Startup.cs 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);
            //配置Swagger
            //注册Swagger生成器,定义一个Swagger 文档
            services.AddSwaggerGen (C => 
            { 
                c.SwaggerDoc ( " V1 " , new new Info 
                { 
                    Version = " V1 " , 
                    the Title = " interface document " , 
                    the Description = " a RESTful the API " 
                }); 
                // set xml document annotation path Swagger 
                var xmlFile $ = " {Assembly.GetExecutingAssembly () GetName () the Name..} .xml " ;
                 var= XMLPath Path.Combine (AppContext.BaseDirectory, xmlFile); 
                c.IncludeXmlComments (XMLPath); 
            }); 
        } 

        // This Method Called by the gets the Use The Runtime the this Method to the HTTP Request The Configure Pipeline.. 
        public  void the Configure (App IApplicationBuilder , IHostingEnvironment the env) 
        { 
            IF (env.IsDevelopment ()) 
            { 
                app.UseDeveloperExceptionPage (); 
            } 
            // enable generation middleware services Swagger 
            app.UseSwagger ();
             // enable generation middleware services Swagger, Swagger JSON endpoint specified 
            app .UseSwaggerUI (C => 
            {
                c.SwaggerEndpoint ( " /swagger/v1/swagger.json " , " the Web Vl the App " ); 
                c.RoutePrefix = String .Empty; // set the root access 
            }); 
            app.UseMvc (); 
        } 
    } 
}

  Then, right-project, click Properties.

  Select Generate, Debug choose our path.

  Check the XML document file, auto-fill, then there will be a warning (non-OCD can ignore the warning)

  Want to get rid of the warning, cancel the display just above the warning added 1591 shown above, Ctrl + S to save it, a warning is gone.

  Then click Debug, will start the browser behind url removed.

  When finished, run directly VS, will enter the document UI page.

The use of Swagger

  We open the first method, click the button Try it out.

  This method is no argument, just click Execute execution.

  After the execution can see the contents Response body returned.

  Click the second method, two given parameters, perform input, returns the result obtained.

  The third method is the parameter model, to pass json format, the default has generated good, we just need to change it to edit the value, and then executed on the line.

V. Summary

  .NET Core Api here to set up and simple to use came to an end, this post to learn how to create .NET Core Api project and how to build Swagger document generation and use, then I will continue to learn and use .NET Core Api, and which process is recorded. In this title I had wanted to add (a), but there may be more recently thought not, and so after it is more a plus. Ei (▔, ▔) ㄏ 

Guess you like

Origin www.cnblogs.com/LYF1997/p/11473967.html