Hướng dẫn asp net core web api with mysql database - api web lõi asp net với cơ sở dữ liệu mysql

Hướng dẫn này sẽ đi qua ứng dụng API ASP.NET Core JSON cơ bản thực hiện các hoạt động CRUD trên các bài đăng trên blog.

Khởi tạo MySQL

Tạo cơ sở dữ liệu MySQL và sao chép SQL sau để tạo bảng có tên BlogPost:

CREATE SCHEMA blog;
USE blog;

CREATE TABLE IF NOT EXISTS `BlogPost` [
  Id INT NOT NULL AUTO_INCREMENT,
  Content LONGTEXT CHARSET utf8mb4,
  Title LONGTEXT CHARSET utf8mb4,
  PRIMARY KEY [`Id`]
] ENGINE=InnoDB;

Khởi tạo API Web ASP.NET Core

Tạo một thư mục có tên BlogPostApi, sau đó chạy

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
0 tại gốc để tạo dự án ban đầu. Chạy
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
1. Bạn nên có một dự án làm việc tại thời điểm này, sử dụng
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
2 để xác minh các bản dựng dự án và chạy thành công.

Cập nhật tệp cấu hình

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
3 giữ các cấp độ ghi nhật ký .NET Core và chuỗi kết nối ADO.NET:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
4 là đối tượng cơ sở dữ liệu ứng dụng dùng một lần, được điều chỉnh để đọc ConnectionString từ đối tượng cấu hình:

using System;
using MySqlConnector;

namespace BlogPostApi
{
    public class AppDb : IDisposable
    {
        public MySqlConnection Connection { get; }

        public AppDb[string connectionString]
        {
            Connection = new MySqlConnection[connectionString];
        }

        public void Dispose[] => Connection.Dispose[];
    }
}

.NET Core Startup

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
5 chứa các dịch vụ cấu hình và khung thời gian chạy. Thêm cuộc gọi này vào
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
6 để thực hiện một thể hiện
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
7 có sẵn cho các phương thức điều khiển.

services.AddTransient[_ => new AppDb[Configuration["ConnectionStrings:DefaultConnection"]]];

Bây giờ ứng dụng của chúng tôi được cấu hình và chúng tôi có thể tập trung vào việc viết chức năng cốt lõi!

Mô hình

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
8 đại diện cho một bài đăng trên blog duy nhất và chứa các phương thức chèn, cập nhật và xóa.

using System.Data;
using System.Threading.Tasks;
using MySqlConnector;

namespace BlogPostApi
{
    public class BlogPost
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        internal AppDb Db { get; set; }

        public BlogPost[]
        {
        }

        internal BlogPost[AppDb db]
        {
            Db = db;
        }

        public async Task InsertAsync[]
        {
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"INSERT INTO `BlogPost` [`Title`, `Content`] VALUES [@title, @content];";
            BindParams[cmd];
            await cmd.ExecuteNonQueryAsync[];
            Id = [int] cmd.LastInsertedId;
        }

        public async Task UpdateAsync[]
        {
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"UPDATE `BlogPost` SET `Title` = @title, `Content` = @content WHERE `Id` = @id;";
            BindParams[cmd];
            BindId[cmd];
            await cmd.ExecuteNonQueryAsync[];
        }

        public async Task DeleteAsync[]
        {
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"DELETE FROM `BlogPost` WHERE `Id` = @id;";
            BindId[cmd];
            await cmd.ExecuteNonQueryAsync[];
        }

        private void BindId[MySqlCommand cmd]
        {
            cmd.Parameters.Add[new MySqlParameter
            {
                ParameterName = "@id",
                DbType = DbType.Int32,
                Value = Id,
            }];
        }

        private void BindParams[MySqlCommand cmd]
        {
            cmd.Parameters.Add[new MySqlParameter
            {
                ParameterName = "@title",
                DbType = DbType.String,
                Value = Title,
            }];
            cmd.Parameters.Add[new MySqlParameter
            {
                ParameterName = "@content",
                DbType = DbType.String,
                Value = Content,
            }];
        }
    }
}

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
9 chứa các lệnh để truy vấn các bài đăng trên blog từ cơ sở dữ liệu:

using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
using MySqlConnector;

namespace BlogPostApi
{
    public class BlogPostQuery
    {
        public AppDb Db { get; }

        public BlogPostQuery[AppDb db]
        {
            Db = db;
        }

        public async Task FindOneAsync[int id]
        {
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"SELECT `Id`, `Title`, `Content` FROM `BlogPost` WHERE `Id` = @id";
            cmd.Parameters.Add[new MySqlParameter
            {
                ParameterName = "@id",
                DbType = DbType.Int32,
                Value = id,
            }];
            var result = await ReadAllAsync[await cmd.ExecuteReaderAsync[]];
            return result.Count > 0 ? result[0] : null;
        }

        public async Task LatestPostsAsync[]
        {
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"SELECT `Id`, `Title`, `Content` FROM `BlogPost` ORDER BY `Id` DESC LIMIT 10;";
            return await ReadAllAsync[await cmd.ExecuteReaderAsync[]];
        }

        public async Task DeleteAllAsync[]
        {
            using var txn = await Db.Connection.BeginTransactionAsync[];
            using var cmd = Db.Connection.CreateCommand[];
            cmd.CommandText = @"DELETE FROM `BlogPost`";
            await cmd.ExecuteNonQueryAsync[];
            await txn.CommitAsync[];
        }

        private async Task ReadAllAsync[DbDataReader reader]
        {
            var posts = new List[];
            using [reader]
            {
                while [await reader.ReadAsync[]]
                {
                    var post = new BlogPost[Db]
                    {
                        Id = reader.GetInt32[0],
                        Title = reader.GetString[1],
                        Content = reader.GetString[2],
                    };
                    posts.Add[post];
                }
            }
            return posts;
        }
    }
}

Người điều khiển

using System;
using MySqlConnector;

namespace BlogPostApi
{
    public class AppDb : IDisposable
    {
        public MySqlConnection Connection { get; }

        public AppDb[string connectionString]
        {
            Connection = new MySqlConnection[connectionString];
        }

        public void Dispose[] => Connection.Dispose[];
    }
}
0 Tiếp xúc các điểm cuối API ASYNC cho các hoạt động CRUD trên các bài đăng trên blog:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace BlogPostApi.Controllers
{
    [Route["api/[controller]"]]
    public class BlogController : ControllerBase
    {
        public BlogController[AppDb db]
        {
            Db = db;
        }

        // GET api/blog
        [HttpGet]
        public async Task GetLatest[]
        {
            await Db.Connection.OpenAsync[];
            var query = new BlogPostQuery[Db];
            var result = await query.LatestPostsAsync[];
            return new OkObjectResult[result];
        }

        // GET api/blog/5
        [HttpGet["{id}"]]
        public async Task GetOne[int id]
        {
            await Db.Connection.OpenAsync[];
            var query = new BlogPostQuery[Db];
            var result = await query.FindOneAsync[id];
            if [result is null]
                return new NotFoundResult[];
            return new OkObjectResult[result];
        }

        // POST api/blog
        [HttpPost]
        public async Task Post[[FromBody]BlogPost body]
        {
            await Db.Connection.OpenAsync[];
            body.Db = Db;
            await body.InsertAsync[];
            return new OkObjectResult[body];
        }

        // PUT api/blog/5
        [HttpPut["{id}"]]
        public async Task PutOne[int id, [FromBody]BlogPost body]
        {
            await Db.Connection.OpenAsync[];
            var query = new BlogPostQuery[Db];
            var result = await query.FindOneAsync[id];
            if [result is null]
                return new NotFoundResult[];
            result.Title = body.Title;
            result.Content = body.Content;
            await result.UpdateAsync[];
            return new OkObjectResult[result];
        }

        // DELETE api/blog/5
        [HttpDelete["{id}"]]
        public async Task DeleteOne[int id]
        {
            await Db.Connection.OpenAsync[];
            var query = new BlogPostQuery[Db];
            var result = await query.FindOneAsync[id];
            if [result is null]
                return new NotFoundResult[];
            await result.DeleteAsync[];
            return new OkResult[];
        }

        // DELETE api/blog
        [HttpDelete]
        public async Task DeleteAll[]
        {
            await Db.Connection.OpenAsync[];
            var query = new BlogPostQuery[Db];
            await query.DeleteAllAsync[];
            return new OkResult[];
        }

        public AppDb Db { get; }
    }
}

Chạy ứng dụng

Xin chúc mừng, bạn nên có một ứng dụng đầy đủ chức năng vào thời điểm này! Bạn sẽ có thể chạy

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "DefaultConnection": "Server=127.0.0.1;User ID=root;Password=pass;Port=3306;Database=blog"
    }
}
2 để bắt đầu ứng dụng của bạn.

Các điểm cuối API sau đây sẽ hoạt động. Lưu ý để đặt các tiêu đề

using System;
using MySqlConnector;

namespace BlogPostApi
{
    public class AppDb : IDisposable
    {
        public MySqlConnection Connection { get; }

        public AppDb[string connectionString]
        {
            Connection = new MySqlConnection[connectionString];
        }

        public void Dispose[] => Connection.Dispose[];
    }
}
2 trên các phương thức
using System;
using MySqlConnector;

namespace BlogPostApi
{
    public class AppDb : IDisposable
    {
        public MySqlConnection Connection { get; }

        public AppDb[string connectionString]
        {
            Connection = new MySqlConnection[connectionString];
        }

        public void Dispose[] => Connection.Dispose[];
    }
}
3 và
using System;
using MySqlConnector;

namespace BlogPostApi
{
    public class AppDb : IDisposable
    {
        public MySqlConnection Connection { get; }

        public AppDb[string connectionString]
        {
            Connection = new MySqlConnection[connectionString];
        }

        public void Dispose[] => Connection.Dispose[];
    }
}
4.

POST //localhost:5001/api/blog
{ "Title": "One", "Content": "First Blog Post!" }

POST //localhost:5001/api/blog
{ "Title": "Two", "Content": "Second Blog Post!" }

POST //localhost:5001/api/blog
{ "Title": "Three", "Content": "Third Blog Post!" }

GET //localhost:5001/api/blog
// Output:
[
    { "id": 3, "title": "Three", "content": "Third Blog Post!" },
    { "id": 2, "title": "Two", "content": "Second Blog Post!" },
    { "id": 1, "title": "One", "content": "First Blog Post!"}
]

DELETE //localhost:5001/api/blog/1
// blog post 1 is gone

PUT //localhost:5001/api/blog/2
{ "Title": "Two", "Content": "Second Blog Post Revised" }

GET //localhost:5001/api/blog
// Output:
[
    { "id": 3, "title": "Three", "content": "Third Blog Post!" },
    { "id": 2, "title": "Two", "content": "Second Blog Post Revised" },
]

DELETE //localhost:5001/api/blog
// all blog posts are gone

GET //localhost:5001/api/blog
// Output:
[]

Làm cách nào để kết nối cơ sở dữ liệu MySQL với API Core Web?

Cách kết nối với MySQL từ ...
Cài đặt MySQLConnector. Đầu tiên, cài đặt gói nuget mysqlconnector. ....
Chuỗi kết nối. Một chuỗi kết nối điển hình cho mysql là: server = yourserver; id id = yourUserId; password = yourPassword; cơ sở dữ liệu = yourdatabase. ....
Cấu hình dịch vụ [ASP.NET Core] ....
Mở và sử dụng kết nối ..

Bạn có thể sử dụng MySQL với .NET Core không?

Net Core và MySQL đều là công nghệ nguồn miễn phí và nguồn mở. Core ASP.NET mới có thể chạy trên Linux và trong các thùng chứa Linux và MySQL là một trong những cơ sở dữ liệu dễ dàng nhất để bắt đầu. Điều này làm cho sự kết hợp của ASP.NET Core và MySQL trở thành một sự kết hợp khá hấp dẫn.MySQL is one of the easiest databases to get started with. This makes the combination of ASP.NET Core and MySQL a pretty compelling combination.

ASP.NET Core có API web không?

ASP.NET Core hỗ trợ Tạo API Web bằng bộ điều khiển hoặc sử dụng API tối thiểu.Bộ điều khiển trong API Web là các lớp xuất phát từ cơ sở điều khiển.. Controllers in a web API are classes that derive from ControllerBase.

ASP Net có thể kết nối với MySQL không?

Để kết nối với cơ sở dữ liệu MySQL bằng cách sử dụng ASP.NET, hãy tìm chuỗi kết nối cơ sở dữ liệu của bạn [PLESK].Lưu ý: Thay đổi giá trị mật khẩu của bạn thành giá trị mật khẩu cơ sở dữ liệu thực của bạn.Sử dụng Microsoft Visual Studio.Net tạo một dự án ASP.NET.Find your database's connection strings [Plesk]. Note: Change the your password value to your real database password value. Using Microsoft Visual Studio . NET create an ASP.NET Project.

Bài Viết Liên Quan

Chủ Đề