NetCore 笔记
Net6 是第一个稳定,长期支持版本(startup+program)
Net8 是第二个稳定,长期支持版本(program)
1. 注册上下文Session
var builder = WebApplication.CreateBuilder(args); builder.Services.AddSession(); var app = builder.Build(); app.UseSession();
2. 注册NLog , 引用 NLog.Web.AspNetCore 引用, 设置配置文件,和MVC相同
builder.Logging.AddNLog("NLog/NLog.config");
写入帮助类,
public static class LogHelper { private static Logger logger; static LogHelper() { logger = LogManager.GetCurrentClassLogger(); } /// <summary> /// 写入错误日志 /// </summary> /// <param name="message"></param> public static void WriteError(string message) { logger.Log(LogLevel.Error, message); } /// <summary> /// 写入操作日志 /// </summary> /// <param name="message"></param> public static void WriteInfo(string message) { logger.Log(LogLevel.Info, message); } }
-- 增加注释
-- 增加发布版本
-- JWT 是一个Token发布平台
Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true,//保存token,后台验证token是否生效(重要) ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = AppSetting.Secret.Audience,//Audience ValidIssuer = AppSetting.Secret.Issuer,//Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret.JWT)) }; options.Events = new JwtBearerEvents() { OnChallenge = context => { context.HandleResponse(); context.Response.Clear(); context.Response.ContentType = "application/json"; context.Response.StatusCode = 401; context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize()); return Task.CompletedTask; } }; });
services.AddSwaggerGen 下添加
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "JWT授权token前面需要加上字段Bearer与一个空格,如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[] { } } });
大家好,我是新来的小白,文未佳,却已创。转载请声明(博客园-郎中令)出处,谢谢
---市人皆大笑,举手揶揄之(手动链接博客园)