.netcore 跨域+jwt+log4net
跨域
1 2 3 4 5 6 7 8 9 10 11 12 | #region CORS 跨域 services.AddCors(options => { options.AddPolicy( "any" , builder => { builder .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin(); }); }); |
1 2 | // 允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称 app.UseCors( "any" );<br>app.UseFileServer();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization(); |
jwt
安装 包 Microsoft.AspNetCore.Authentication.JwtBearer(5.0.17)
Microsoft.AspNetCore.Mvc.NewtonsoftJson(5.0.17)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #region Jwt配置 // 注册JWT服务 services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true , //是否验证Issuer ValidIssuer = Configuration[ "Jwt:Issuer" ], //发行人Issuer ValidateAudience = true , //是否验证Audience ValidAudience = Configuration[ "Jwt:Audience" ], //订阅人Audience ValidateIssuerSigningKey = true , //是否验证SecurityKey IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[ "Jwt:SecretKey" ])), //SecurityKey ValidateLifetime = true , //是否验证失效时间 ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒) RequireExpirationTime = true , }; }); //设置日期格式 services.AddControllers() .AddNewtonsoftJson(op => { //Newtonsoft.Json op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss" ; op.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; }); services.AddSingleton( new JwtHelper(Configuration)); #endregion |
新建一个类 JwtHelper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public class JwtHelper { private readonly IConfiguration _configuration; public JwtHelper(IConfiguration configuration) { _configuration = configuration; } public string CreateToken() { // 1. 定义需要使用到的Claims var claims = new [] { new Claim(ClaimTypes.Name, "u_admin" ), //HttpContext.User.Identity.Name new Claim(ClaimTypes.Role, "r_admin" ), //HttpContext.User.IsInRole("r_admin") new Claim(JwtRegisteredClaimNames.Jti, "admin" ), new Claim( "Username" , "Admin" ), new Claim( "Name" , "超级管理员" ) }; // 2. 从 appsettings.json 中读取SecretKey var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[ "Jwt:SecretKey" ])); // 3. 选择加密算法 var algorithm = SecurityAlgorithms.HmacSha256; // 4. 生成Credentials var signingCredentials = new SigningCredentials(secretKey, algorithm); // 5. 根据以上,生成token var jwtSecurityToken = new JwtSecurityToken( _configuration[ "Jwt:Issuer" ], //Issuer _configuration[ "Jwt:Audience" ], //Audience claims, //Claims, DateTime.Now, //notBefore DateTime.Now.AddSeconds(30), //expires signingCredentials //Credentials ); // 6. 将token变为string var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); return token; } } |
在appsetting.json中添加
1 2 3 4 5 | "Jwt" : { "SecretKey" : "745058532@qq.com" , "Issuer" : "WebAppIssuer" , "Audience" : "WebAppAudience" } |
log4net
在program文件中加入
1 2 3 4 5 6 7 8 9 10 | public static IHostBuilder CreateHostBuilder( string [] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { loggingBuilder.AddLog4Net( "log4net.config" ); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); |
创建log4net.config文件
安装 包 Microsoft.Extensions.Logging.Log4Net.AspNetCore(6.13)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?xml version= "1.0" encoding= "utf-8" ?> <log4net> <!-- Define some output appenders --> <appender name= "rollingAppender" type= "log4net.Appender.RollingFileAppender" > <file value= "log\log.txt" /> <!--追加日志内容--> <appendToFile value= "true" /> <!--防止多线程时不能写Log,官方说线程非安全--> <lockingModel type= "log4net.Appender.FileAppender+MinimalLock" /> <!--可以为:Once|Size|Date|Composite--> <!--Composite为Size和Date的组合--> <rollingStyle value= "Composite" /> <!--当备份文件时,为文件名加的后缀--> <datePattern value= "yyyyMMdd.TXT" /> <!--日志最大个数,都是最新的--> <!--rollingStyle节点为Size时,只能有value个日志--> <!--rollingStyle节点为Composite时,每天有value个日志--> <maxSizeRollBackups value= "20" /> <!--可用的单位:KB|MB|GB--> <maximumFileSize value= "3MB" /> <!--置为 true ,当前最新日志文件名永远为file节中的名字--> <staticLogFileName value= "true" /> <!--输出级别在INFO和ERROR之间的日志--> <filter type= "log4net.Filter.LevelRangeFilter" > <param name= "LevelMin" value= "ALL" /> <param name= "LevelMax" value= "FATAL" /> </filter> <layout type= "log4net.Layout.PatternLayout" > <conversionPattern value= "%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <root> <priority value= "ALL" /> <level value= "ALL" /> <appender- ref ref = "rollingAppender" /> </root> </log4net> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!