记一次使用Asp.Net Core WebApi 5.0+Dapper+Mysql+Redis+Docker的开发过程 (5)

```c#
// 如果有几十个属性是相当的可怕的
var users = new Users
{
Email = user.Email,
Password = user.Password,
UserName = user.UserName
};
// 使用Automapper就容易多了
var model = _mapper.Map<Users>(user);
```

先安装依赖包

![Automapper](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6a9feb69dca04ae983e215868610c5ff~tplv-k3u1fbpfcp-zoom-1.image)

在项目根目录的 AutoMapper 文件夹中 新建 AutoMapperConfig 类,来管理我们的映射关系。

```c#
using AutoMapper;
using CodeUin.Dapper.Entities;
using CodeUin.WebApi.Models;

namespace CodeUin.WebApi.AutoMapper
{
public class AutoMapperConfig : Profile
{
public AutoMapperConfig()
{
CreateMap<UserRegisterModel, Users>().ReverseMap();
CreateMap<UserLoginModel, Users>().ReverseMap();
CreateMap<UserLoginModel, UserModel>().ReverseMap();
CreateMap<UserModel, Users>().ReverseMap();
}
}
}
```

最后,在 Startup 文件的 ConfigureServices 方法中 添加 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()) 即可。

#### 使用JWT

下面将集成JWT,来处理授权等信息。首先,需要安装依赖包。

![JWT](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2705846832bc48ff84bb536eecbeee9c~tplv-k3u1fbpfcp-zoom-1.image)

修改 appsttings.json 文件,添加 Jwt 配置信息。

```c#
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Jwt": {
"Key": "e816f4e9d7a7be785a", // 这个key必须大于16位数,非常生成的时候会报错
"Issuer": "codeuin.com"
}
}
```

最后,在 Startup 类的 ConfigureServices 方法中添加 Jwt 的使用。

```c#
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5), //缓冲过期时间 默认5分钟
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
```

好了,最终我们的 Startup 类是这样子的,关于自定义的参数验证后面会讲到。

```c#
using Autofac;
using AutoMapper;
using CodeUin.WebApi.Autofac;
using CodeUin.WebApi.Filters;
using CodeUin.WebApi.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;

namespace CodeUin.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureContainer(ContainerBuilder builder)
{
// 依赖注入
builder.RegisterModule(new CustomAutofacModule());
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5), //缓冲过期时间 默认5分钟
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

services.AddHttpContextAccessor();

// 使用AutoMapper
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

// 关闭参数自动校验
services.Configure<ApiBehaviorOptions>((options) =>
{
options.SuppressModelStateInvalidFilter = true;
});

// 使用自定义验证器
services.AddControllers(options =>
{
options.Filters.Add<ValidateModelAttribute>();
}).
AddJsonOptions(options =>
{
// 忽略null值
options.JsonSerializerOptions.IgnoreNullValues = true;
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

// 请求错误提示配置
app.UseErrorHandling();

// 授权
app.UseAuthentication();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
```

#### 新建实体类

我将新建三个实体类,分别是 UserLoginModel 用户登录,UserRegisterModel 用户注册,UserModel 用户基本信息。

UserLoginModel 和 UserRegisterModel 将根据我们在属性中配置的特性自动验证合法性,就不需要在控制器中单独写验证逻辑了,极大的节省了工作量。

```c#
using System;
using System.ComponentModel.DataAnnotations;

namespace CodeUin.WebApi.Models
{
/// <summary>
/// 用户实体类
/// </summary>
public class UserModel
{
public int Id { get; set; }

public string Email { get; set; }
public string UserName { get; set; }

public string Mobile { get; set; }

public int Gender { get; set; }

public int Age { get; set; }

public string Avatar { get; set; }
}

public class UserLoginModel
{
[Required(ErrorMessage = "请输入邮箱")]
public string Email { get; set; }

[Required(ErrorMessage = "请输入密码")]
public string Password { get; set; }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyjffj.html