ASP.NET Core 3.1 WebApi+JWT+Swagger+EntityFrameworkCore构建REST API
2021-03-04 21:26
标签:har from 之间 控制 导致 override date on() object 数据库上下文 DemoContext.cs,在数据库创建时增加一条种子数据admin: UserService实现类: UserController: TokenController: AppHelper中生成token的方法: 运行项目,浏览器访问: ASP.NET Core 3.1 WebApi+JWT+Swagger+EntityFrameworkCore构建REST API 标签:har from 之间 控制 导致 override date on() object 原文地址:https://www.cnblogs.com/xhznl/p/12922690.html一、准备
二、编码
用户表 User.cs:public class User
{
[Key]
public Guid ID { get; set; }
[Required]
[Column(TypeName = "VARCHAR(16)")]
public string UserName { get; set; }
[Required]
[Column(TypeName = "VARCHAR(16)")]
public string Password { get; set; }
}
public class DemoContext : DbContext
{
public DemoContext(DbContextOptions
IUserService接口,这里简单定义几个添加查询的方法:public interface IUserService
{
Task
public class UserService : IUserService
{
private readonly DemoContext context;
public UserService(DemoContext context)
{
this.context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"JwtSetting": {
"SecurityKey": "88d082e6-5672-4c6c-bc42-6fcce20fbf51", // 密钥
"Issuer": "jwtIssuertest", // 颁发者
"Audience": "jwtAudiencetest", // 接收者
"ExpireSeconds": 3600 // 过期时间(3600)
},
"ConnectionStrings": {
"DemoContext": "data source=.;Initial Catalog=WebApiDemoDB;User ID=sa;Password=123456;MultipleActiveResultSets=True;App=EntityFramework"
}
}
///
public static class AppSettings
{
public static JwtSetting JwtSetting { get; set; }
///
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
AppSettings.Init(Configuration);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = AppSettings.JwtSetting.Issuer,
ValidAudience = AppSettings.JwtSetting.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JwtSetting.SecurityKey)),
// 默认允许 300s 的时间偏移量,设置为0
ClockSkew = TimeSpan.Zero,
};
});
services.AddCors(options =>
{
options.AddPolicy("any",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyOrigin()
.AllowAnyHeader();
});
});
services.AddControllers();
services.AddScoped
打开程序包管理控制台:执行命令Add-Migration Initial
然后执行Update-Database
此时数据库已经成功生成:
先建一个数据传输实体,方便统一controller的返回值:public class BaseDto
///
///
public class AppHelper
{
public readonly static AppHelper Instance = new AppHelper();
private AppHelper() { }
///
三、效果
测试一下用户接口:
这时返回401错误,因为我们还没有鉴权
使用admin/123456获取token:
拿到token 点击authorize:
然后再测试用户接口:
此时已经可以正常请求。
代码:https://github.com/xiajingren/NetCore3.1-WebApi-Demo
文章标题:ASP.NET Core 3.1 WebApi+JWT+Swagger+EntityFrameworkCore构建REST API
文章链接:http://soscw.com/index.php/essay/60159.html