C# ASP.NET Core Web API MySQL tutorial (3)

Continue with the next two articles: C# ASP.NET Core Web API Identity Authorization (JWT) Verification (1) blog.csdn.net/u012402739/article/details/128463873

C # ASP.NET Core Web API Redis Tutorial (2 ) details/128465931

Right-click on the project, select Manage NuGet Packages, add (note the version):

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Pomelo.EntityFrameworkCore.MySql

Swashbuckle.AspNetCore

  Open the appsettings.json configuration file and add the following configuration:

  "ConnectionStrings": {
    "DefaultConnection": "Server=127.0.0.1; Port=3306; Database=root; Uid=root; Pwd=123456;"
  }

Add the StudentInfo.cs class in the Models folder: 

The complete code is as follows: 

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace TestApi.Models
{
    public class StudentInfo
    {
        [Key]
        [Column("ID")]
        public int ID { get; set; }
        /// <summary>
        /// 手机号
        /// </summary>
        [Column("Mobile")]
        public string Mobile { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        [Column("Password")]
        public string Password { get; set; }
        /// <summary>
        /// 昵称
        /// </summary>
        [Column("NickName")]
        public string NickName { get; set; }
        /// <summary>
        /// 性别 0=未知 1=男 2=女
        /// </summary>
        [Required]
        [Column("Sex")]
        public int Sex { get; set; }
    }
}

Similarly, in the MySQL database, create a table StudentInfo, the field is the same as [Column("column name")] in StudentInfo.cs, where [Key] represents the primary key.

 Add the MySqlDBHelper.cs class in the Common folder:

 
 
using Microsoft.EntityFrameworkCore;
using TestApi.Models;

namespace TestApi.Common
{
    /// <summary>
    /// mysql类
    /// </summary>
    public partial class MySqlDBHelper : DbContext
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public MySqlDBHelper() { }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="options"></param>
        public MySqlDBHelper(DbContextOptions<MySqlDBHelper> options) : base(options) { }
        /// <summary>
        /// StudentInfo表映射
        /// </summary>
        public DbSet<StudentInfo> StudentInfo { get; set; }

        /*
            如果有多个表,则同方法创建即可
            public DbSet<User> User { get; set; }
            public DbSet<Test> Test { get; set; }
         */
    }
}

Add service dependencies in the Program.cs class:

#region MySQL服务
// MySQL服务
builder.Services.AddDbContext<MySqlDBHelper>(opt => {
    string connectionString = builder.Configuration.GetSection("ConnectionStrings:DefaultConnection").Value;
    var serverVersion = ServerVersion.AutoDetect(connectionString);
    opt.UseMySql(connectionString, serverVersion);
});
#endregion

Test use, use in the controller interface, open UserInfoController.cs and add code:

 

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TestApi.Common;
using TestApi.Models;

namespace TestApi.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class UserInfoController : ControllerBase
    {
        private readonly JwtHelper _jwt;
        private readonly RedisHelper _redis;
        private readonly MySqlDBHelper _mysqlDb;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="jwtHelper"></param>
        public UserInfoController(JwtHelper jwtHelper, RedisHelper redis, MySqlDBHelper mySqlDb)
        {
            _jwt = jwtHelper;
            _redis = redis;
            _mysqlDb = mySqlDb;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetToken(UserInfo user)
        {
            //参数验证等等....
            if (string.IsNullOrEmpty(user.UserName))
            {
                return Ok("参数异常!");
            }
            //这里可以连接mysql数据库做账号密码验证
            StudentInfo newData = _mysqlDb.StudentInfo.FirstOrDefault(stu => stu.Mobile == user.UserName && stu.Password == user.Password);
            if (newData == null)
            {
                return Ok("账号不存在或者密码错误!");
            }
            else
            {
                //账号存在
            }
            //这里可以做Redis缓存验证等等
            _redis.GetDatabase().StringSet("Name", user.UserName);// 往Redis里面存入数据
            string name = _redis.GetDatabase().StringGet("Name");// 从Redis里面取数据

            //这里获取Token,当然,这里也可以选择传结构体过去
            var token = _jwt.CreateToken(user.UserName, user.PhoneNumber);
            return Ok(token);
        }
        /// <summary>
        /// 获取自己的详细信息,其中 [Authorize] 就表示要带Token才行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult GetSelfInfo()
        {
            //执行到这里,就表示已经验证授权通过了
            /*
             * 这里返回个人信息有两种方式
             * 第一种:从Header中的Token信息反向解析出用户账号,再从数据库中查找返回
             * 第二种:从Header中的Token信息反向解析出用户账号信息直接返回,当然,在前面创建Token时,要保存进使用到的Claims中。
            */
            return Ok("授权通过了!");
        }
    }
}

Then you can F5 to do the test.

The next article will introduce the use of Docker:

C# ASP.NET Core Web API Docker tutorial (4)_How to use c# docker

Guess you like

Origin blog.csdn.net/u012402739/article/details/128467070
Recommended