1、准备工作:
1.1、新建Users的控制器、接口、服务层文件;
1.2、注入接口与服务层关系
builder.Services.AddTransient<IUsersService, UsersService>();
1.3、添加MD5加密规则
public static string GetMd5Hash(string input){//using System.Security.Cryptography;using (MD5 md5 = MD5.Create()){byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));StringBuilder sb = new StringBuilder();for (int i = 0; i < data.Length; i++){sb.Append(data[i].ToString("x2"));}return sb.ToString();}}
2、代码:
2.1、控制器层:
/// <summary>
/// 用户管理
/// </summary>
[ApiVersionCustomRoute(SwaggerDocSettings.ApiVersions.v1)]
[ApiController]
public class UsersController : ControllerBase
{private readonly ILogger<UsersController> _logger;private readonly IUsersService _usersService;/// <summary>/// 构造函数/// </summary>/// <param name="logger"></param>public UsersController(ILogger<UsersController> logger, IUsersService usersService){_logger = logger;_usersService = usersService;}/// <summary>/// 登录/// </summary>/// <param name="para">入参</param>/// <returns></returns>[ApiVersionCustomRoute("Login", SwaggerDocSettings.ApiVersions.v1)][HttpPost]public async Task<ApiResult> GetUser(LoginUserParameters para){//验证if (string.IsNullOrWhiteSpace(para.UserName) || string.IsNullOrWhiteSpace(para.PassWord)){return ApiResultHelper.Error("请输入账号或密码!");}var result = await _usersService.GetUser(para);return result;}/// <summary>/// 注册/// </summary>/// <param name="para">入参</param>/// <returns></returns>[ApiVersionCustomRoute("Register", SwaggerDocSettings.ApiVersions.v1)][HttpPost]public async Task<ApiResult> AddUser(RegisterUserParameters para){//验证(ps:邮箱验证码先搁置)if (string.IsNullOrWhiteSpace(para.UserName) || string.IsNullOrWhiteSpace(para.PassWord)){return ApiResultHelper.Error("请输入账号或密码!");}var result = await _usersService.AddUser(para);return result;}
}
2.2、接口层:
public interface IUsersService
{Task<ApiResult> GetUser(LoginUserParameters login);Task<ApiResult> AddUser(RegisterUserParameters register);
}
2.3、服务层:
public async Task<ApiResult> AddUser(RegisterUserParameters para){//1、查询数据var entity = await _usersRep.Context.Queryable<Users>().Where(t => t.UserName == para.UserName).FirstAsync();if (entity != null){return ApiResultHelper.Error("用户名已被占用!");}//2、构建实体var md5Pwd = MD5Helper.GetMd5Hash(para.PassWord);Users user = new Users(){UserName = para.UserName,PassWord = md5Pwd,PhoneNumber = "",Email = para.Email,UserStatus = UsersEnum_UserStatus.ok,Gender = UsersEnum_Gender.secrecy,OpenId = "",Avatar = "",//后添加个头像库Admire = "",SubScribe ="",Introduction = "",UserType = UsersEnum_UserType.other,CreateBy = 0,CreateTime = DateTime.Now,UpdateBy = 0,UpdateTime = null,};//3、执行新增var bl = await _usersRep.InsertAsync(user);//4、返回结果if (!bl){return ApiResultHelper.Error("注册失败!请联系博主");}return ApiResultHelper.Success(bl);}public async Task<ApiResult> GetUser(LoginUserParameters para){var md5Pwd = MD5Helper.GetMd5Hash(para.PassWord);//1、查询数据var entity = await _usersRep.Context.Queryable<Users>().Where(t => t.UserName == para.UserName && t.PassWord == md5Pwd).FirstAsync();if (entity == null){return ApiResultHelper.Error("账号或密码错误!");}//2、生成tokenJwtClaim jwtClaim = new JwtClaim(){Id = entity.Id.ToString(),Name = entity.UserName,NickName = entity.UserName,UserType = ((int)entity.UserType).ToString(),Roles = "",Menus = ""};var token = JwtHelper.GenerateToken(jwtClaim);return ApiResultHelper.Success(token);}
3、测试:
这里不再赘述了,(已测试通过)
4、拓展:
4.1、添加相关日志记录
4.1、登录接口限流(后续新建文章补充)