Net Core makes a simple instance of webApi

Do a simple instance with NetCore and Dapper and mySql,

a preparation

1: VS2017+windos system, other operating systems and tools can also be used

2: A Cenetos virtual machine or virtual machine

Two: start

1: Transform with Microsoft's official netCore ToDo project. The main structure of the project is as shown below, and the source is connected.

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api

 

1: Open the Nuget console, install the MySQL official .NET Core driver, and support EF Core

 >Install-Package SapientGuardian.MySql.Data -Pre

2: Open the Nuget console and install Dapper

>Install-Package Dapper -Pre

3: Create a new ToDoItem entity in the Models folder

public class ToDoItem
    {
        [Required]
        public string ID { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Notes { get; set; }

        public bool Done { get; set; }
    }

4: Configure the database connection string of MySql in appsettings.json, and then click the properties of appsettings.json to change the value of "Copy to output directory" to "Copy always",

The role of SslMode=none is to solve the SSL error when connecting
  "ConnectionStrings": {
    "SqlServerConnection": "Server=(LocalDb)\\MSSQLLocalDB, Database=test",
    "MySqlConnection": "Server=your own server;Database=test;User ID=root;Password=111111;SslMode=none"
  }

 5: Create a new AppConfigurtaionServices class under Common to read the connection string in appsettings.json (if the appsettings.json property is not selected, always copy, when the code is running,

IConfiguration will report an error

)

public class AppConfigurtaionServices
    {
        public static IConfiguration Configuration { get; set; }
        static AppConfigurtaionServices()
        {
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }
    }

6: Create a new Interfaces folder, and then build an interface class of IToDoRepository below

public interface IToDoRepository
    {
        bool DoesItemExist(string id);
        IEnumerable<ToDoItem> All();
        ToDoItem Find(string id);
        int Insert(ToDoItem item);
        int Update(ToDoItem item);
        int Delete(string id);
    }

  

7: Create a new Service and then create a new ToDoRepository class below, which is our data storage class, remember to reference (using Dapper; and using MySql.Data.MySqlClient;)

public class ToDoRepository : IToDoRepository
    {
        private  static  string DefaultSqlConnectionString = "";
        public ToDoRepository()
        {
            DefaultSqlConnectionString = AppConfigurtaionServices.Configuration.GetConnectionString("MySqlConnection");
    
        }
        public static IDbConnection GetSqlConnection(string sqlConnectionString = null)
        {
            if (string.IsNullOrWhiteSpace(sqlConnectionString))
            {
                sqlConnectionString = DefaultSqlConnectionString;
            }
            IDbConnection conn = new MySqlConnection(sqlConnectionString);
            conn.Open();
            return conn;
        }
        /// <summary>
        /// Get all
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ToDoItem> All()
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                string strsql = "select * from ToDoItem";
                return conn.Query<ToDoItem>(strsql, null);
            }
        }

        /// <summary>
        /// Check if it exists
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DoesItemExist(string id)
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                int cout = conn.Query<int>("select count(*) from ToDoItem where  ID=@ID", new { ID = id }).FirstOrDefault();
                if (cout > 0)
                    return true;
                else
                    return false;
            }
        }
        /// <summary>
        /// delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(string id)
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                string strsql = "DELETE from ToDoItem where ID=@ID";
                return conn.Execute(strsql, new { ID = id });
            }

        }

        /// <summary>
        /// Query the entire object
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ToDoItem Find(string id)
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                string strsql = "select * from  ToDoItem where ID=@ID";
                return conn.Query<ToDoItem>(strsql, new { ID = id }).FirstOrDefault();
            }
        }
        /// <summary>
        /// Add item
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int Insert(ToDoItem item)
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                string strsql = "INSERT into ToDoItem(ID,Name,Notes,Done)values(@ID,@Name,@Notes,@Done)";
                return conn.Execute(strsql, item);
            }
        }

        /// <summary>
        /// Revise
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int Update(ToDoItem item)
        {
            using (IDbConnection conn = GetSqlConnection())
            {
                string strsql = " UPDATE ToDoItem SET Name=@Name,Notes=@Notes,Done=@Done where ID=@ID";
                return conn.Execute(strsql, item);
            }
        }

     

    }

 8: Add a ToDoItemsController controller under the Controller, remember to add the relevant namespace

[Route("api/[controller]")]
    public class ToDoItemsController : Controller
    {
        private readonly IToDoRepository _toDoRepository;

        public ToDoItemsController(IToDoRepository toDoRepository)
        {
            _toDoRepository = toDoRepository;
        }

        /// <summary>
        /// retrieve data
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return Ok(_toDoRepository.All());
        }
        /// <summary>
        /// Add item
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Create([FromBody] ToDoItem item)
        {
            try
            {
                if (item == null || !ModelState.IsValid)
                {
                    return BadRequest("Not verified");
                }
                bool itemExists = _toDoRepository.DoesItemExist(item.ID);
                if (itemExists)
                {
                    return StatusCode(StatusCodes.Status409Conflict, "This item already exists");
                }
                _toDoRepository.Insert(item);
            }
            catch (Exception)
            {
                return BadRequest("Create failed");
            }

            return Ok(item);
        }

        /// <summary>
        /// Modified item
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Edit([FromBody] ToDoItem item)
        {
            try
            {
                if(item==null || !ModelState.IsValid)
                    return BadRequest("Failed to pass required verification");
                var existingItem = _toDoRepository.Find(item.ID);
                if(existingItem==null)
                {
                    return NotFound("The record was not found");
                }
                _toDoRepository.Update(item);
            }
            catch(Exception)
            {
                return BadRequest("Modification failed");
            }
            return NoContent();
        }

        /// <summary>
        /// delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult Delete(string id)
        {
            try
            {
                var item = _toDoRepository.Find(id);
                if (item == null)
                    return NotFound("No such record");
                _toDoRepository.Delete(id);
            }
            catch(Exception )
            {
                return BadRequest("Deletion failed");
            }

            return NoContent();
        }

     

    }

 9: Configure IToDoRepository and ToDoRepository services in ConfigureServices

   services.AddSingleton<IToDoRepository, Services.ToDoRepository>();

 10: Configure the basic knowledge of Swagger (stocking brother) specific Swagger can be connected to

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio

10.1: Add reference to Nuget console

   >Install-Package Swashbuckle.AspNetCore

10.2: Configure Swagger in the Startup class

10.2.1: Add Swagger service in ConfigureServices method

    //Add Swagger service
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "ToDo API",
                    Description = "A simple example ASP.NET Core Web API",
                    TermsOfService = "None",
                    Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer" },
                    License = new License { Name = "Use under LICX", Url = "https://example.com/license" }
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "ToDoApi.xml");
                c.IncludeXmlComments(xmlPath);
            });

  10.2.2: Configure the Swagger service in Configure

app.UseSwagger();
//Configure the Swagger service
app.UseSwaggerUI(c =>
{
 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

 10.3: The final Startup class is as follows

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using System.IO;
using ToDoApi.Interfaces;

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

        public IConfiguration Configuration { get; }

        //add service
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
   
            //Add Swagger service
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "ToDo API",
                    Description = "A simple example ASP.NET Core Web API",
                    TermsOfService = "None",
                    Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer" },
                    License = new License { Name = "Use under LICX", Url = "https://example.com/license" }
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "ToDoApi.xml");
                c.IncludeXmlComments(xmlPath);
            });
            services.AddSingleton<IToDoRepository, Services.ToDoRepository>();
        }

        // configure the service
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSwagger();
            //Configure the Swagger service
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            //Configure the development environment
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

10.4: The startup item is set to swagger startup 

Make the following modifications in launchSettings.json

This way your project is started with IIS Express and it is the swagger interface

11: Final Effect

11.2: Test the method for obtaining data

12: The understanding of NetCore is still very shallow. I just made a simple demo and hope to help you. I just wrote mysql. If you want to use SqlServer, modify the data connection that reads SqlServerConnection and then store the MySql in the data warehouse. .Data.MySqlClient can be changed to Sql server

 13: demo connection:

https://files.cnblogs.com/files/gouguo/ToDoApi.rar

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017405&siteId=291194637