### Create NuGet Package for Blog.Core Template Source: https://github.com/anjoy8/blog.core/wiki/Temple-Nuget Command to package the Blog.Core webapi template into a NuGet package. This process requires the `nuget.exe` command-line tool and a `.nuspec` file to be present. ```cmd nuget pack Blog.Core.Webapi.Template.nuspec ``` -------------------------------- ### Blog.Core Wiki Navigation Source: https://github.com/anjoy8/blog.core/wiki/Home This section lists key documentation topics available in the project's wiki, covering framework explanations, installation, deployment, database support, and core technical concepts. ```APIDOC Wiki Topics: - Getting Started: https://github.com/anjoy8/Blog.Core/wiki/Getting-Started-with-blogcore - Installation Guide: https://github.com/anjoy8/Blog.Core/wiki/Installation-Guide - Deployment Guide: https://github.com/anjoy8/Blog.Core/wiki/Installation-Publish - Supported Databases: https://github.com/anjoy8/Blog.Core/wiki/support-db - Key Concepts: - AOP: https://github.com/anjoy8/Blog.Core/wiki/AOP - Authorization (JWT/Ids4): https://github.com/anjoy8/Blog.Core/wiki/Authorization-JWT - Caching (MemoryCache, Redis): https://github.com/anjoy8/Blog.Core/wiki/MemoryCache - Dependency Injection (DI-NetCore, DI-AutoFac): https://github.com/anjoy8/Blog.Core/wiki/DI-NetCore - Logging (Log4Net): https://github.com/anjoy8/Blog.Core/wiki/Log4Net-日志集成到-ILogger - ORM (SqlSugar): https://github.com/anjoy8/Blog.Core/wiki/SqlSugar - API Documentation (Swagger): https://github.com/anjoy8/Blog.Core/wiki/Swagger ``` -------------------------------- ### Vue.js and Nuxt.js Articles Source: https://github.com/anjoy8/blog.core/blob/master/README-en.md A collection of articles covering Vue.js basics, component details, actual combat scenarios like building development environments, personal blogs with Axios and Router, Vuex, JWT authentication, SSR, client rendering, and Nuxt.js framework fundamentals and actual combat examples. ```markdown - vue Basics: Style dynamic binding + lifecycle - vue Base Audrey: Component Detail + Project description - vue Actual Combat: development environment to build a "detailed version" - vue Actual Combat: The first edition of the personal blog (axios+router) - vue Actual Combat: Vuex is actually very simple - vuex + JWT Implementation Authorization Authentication Login - Preliminary study on SSR server rendering (personal blog II) - client rendering, server rendering know how much {supplemental} - nuxt Foundation: A preliminary study of the framework - nuxt Basics: Source-oriented research nuxt.js - nuxt Actual Combat: Asynchronous implementation of data dual-end rendering - NUXT actual Combat: Dynamic routing + isomorphism - NUXT Audrey: A probe into permission validation based on Vuex ``` -------------------------------- ### Community and Contribution Source: https://github.com/anjoy8/blog.core/wiki/Home Information on how to get help, report issues, or contribute to the Blog.Core project. It includes links to FAQs, discussion forums, and issue trackers. ```APIDOC Community & Contribution: - FAQ: https://github.com/anjoy8/Blog.Core/wiki/FAQ - Ask a Question: https://www.cnblogs.com/laozhang-is-phi/p/9495618.html#tbCommentBody - Submit an Issue: https://github.com/anjoy8/Blog.Core/issues/new - Open a Pull Request: https://github.com/anjoy8/Blog.Core/compare ``` -------------------------------- ### Use IUser to Get User Info Source: https://github.com/anjoy8/blog.core/wiki/UserInfo Shows how to use the injected IUser interface to access user properties like ID and Name. This allows components to easily retrieve the current user's context. ```csharp module.CreateId = _user.ID; module.CreateBy = _user.Name; ``` -------------------------------- ### Swagger UI Initialization and Configuration Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Gateway/index.html This script configures the Swagger UI interface for API documentation. It sets up essential parameters like the DOM element, presets, and layout, and includes logic to manage OAuth redirection and browser-specific adjustments for Edge. The configuration is dynamically loaded from %(ConfigObject) and %(OAuthConfigObject). ```JavaScript if (window.navigator.userAgent.indexOf("Edge") > -1) { console.log("Removing native Edge fetch in favor of swagger-ui's polyfill") window.fetch = undefined; } var int = null; if (window.location.href.indexOf("docExpansion") < 0) window.location = window.location.href.replace("index.html", "index.html?docExpansion=none"); window.onload = function () { var configObject = JSON.parse('%(ConfigObject)'); var oauthConfigObject = JSON.parse('%(OAuthConfigObject)'); // Apply mandatory parameters configObject.dom_id = "#swagger-ui"; configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]; configObject.layout = "StandaloneLayout"; // If oauth2RedirectUrl isn't specified, use the built-in default if (!configObject.hasOwnProperty("oauth2RedirectUrl")) configObject.oauth2RedirectUrl = window.location.href.replace("index.html", "oauth2-redirect.html"); // Build a system const ui = SwaggerUIBundle(configObject); // Apply OAuth config ui.initOAuth(oauthConfigObject); } ``` -------------------------------- ### Microservices Module Features Source: https://github.com/anjoy8/blog.core/blob/master/README.md Outlines the support for microservices architecture within Blog.Core, including containerization, CI/CD, service discovery, and gateway integration. ```APIDOC Microservices Module: - Containerization with Docker. - CI/CD with Jenkins. - Service discovery with Consul. - Service discovery with Nacos. - Gateway handling with apisix/Ocelot. - Load balancing with Nginx. - Authentication center with Ids4. ``` -------------------------------- ### Blog.Core Project Overview Source: https://github.com/anjoy8/blog.core/wiki/Home This snippet summarizes the core technology stack and architectural approach of the Blog.Core project. It highlights the use of .NET Core 2.2 and a separation of front-end and back-end concerns. ```APIDOC Project: Blog.Core Framework: .NET Core 2.2 Architecture: Full-stack separation (Front-end and Back-end) Description: A project focused on building a blog platform with distinct client and server applications. ``` -------------------------------- ### Swagger UI Initialization and OAuth Configuration Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/index.html Initializes the Swagger UI interface using SwaggerUIBundle, applying configurations for layout, presets, and OAuth. It also includes logic to set a default OAuth redirect URL if not provided. ```javascript var int = null; window.onload = function () { var configObject = JSON.parse('%(ConfigObject)'); var oauthConfigObject = JSON.parse('%(OAuthConfigObject)'); // Apply mandatory parameters configObject.dom_id = "#swagger-ui"; configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]; configObject.layout = "StandaloneLayout"; // If oauth2RedirectUrl isn't specified, use the built-in default if (!configObject.hasOwnProperty("oauth2RedirectUrl")) configObject.oauth2RedirectUrl = window.location.href.replace("index.html", "oauth2-redirect.html"); // Build a system const ui = SwaggerUIBundle(configObject); // Apply OAuth config ui.initOAuth(oauthConfigObject); // Clear element content, here clearing the version selection English text $(".select-label span").empty(); myOnload(); // Modify version translation to Chinese function myOnload() { $(document).ready(function () { $(".select-label span").each(function () { var myvalue = '选择一个接口版本'; $(this).html(myvalue); }); }); } } ``` -------------------------------- ### Login API Endpoint Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/wwwroot/swg-login.html Documentation for the user authentication API endpoint. It handles POST requests with user credentials and redirects upon successful login. ```APIDOC POST /api/Login/swgLogin Description: Authenticates a user with provided credentials. Request Body: Content-Type: application/json Schema: type: object properties: name: { type: string, description: "User's username or email" } pwd: { type: string, description: "User's password" } required: - name - pwd Response: 200 OK: Content-Type: application/json Schema: type: object properties: result: { type: boolean, description: "Indicates if the login was successful" } message: { type: string, description: "Status message" } Success Behavior: If 'result' is true, the user is redirected to 'returnUrl' if provided, otherwise to '/index.html'. Error Behavior: If 'result' is false or parameters are invalid, an alert message is shown. ``` -------------------------------- ### Blog.Core Framework Overview Source: https://github.com/anjoy8/blog.core/blob/master/README.md Provides a high-level overview of the core features and architectural components of the Blog.Core framework. It details the project structure, key technologies used, and the benefits of adopting this framework for enterprise applications. ```APIDOC Project: Blog.Core Description: Enterprise-level full-stack separation framework with .NET Core 6.0 API and Vue 2.x. Key Features: - .NET Core 6.0 API backend - Vue 2.x frontend - RBAC (Role-Based Access Control) permission system - Support for multiple databases (MySql, SqlServer, Sqlite, Oracle, Postgresql, etc.) - SqlSugar ORM integration - Asynchronous programming (async/await) - Five types of logging (Audit, Exception, Request/Response, Service Operation, SQL) - AOP (Aspect-Oriented Programming) for logging, caching, auditing, transactions - Serilog for comprehensive logging - T4 templates or DbFirst for code generation - IdentityServer4 integration for authentication - Multi-tenancy support - SignalR for real-time communication - Redis for caching and message queues - RabbitMQ and Kafka integration - EventBus implementation - API Rate Limiting - Quartz.NET for task scheduling - Swagger for API documentation - MiniProfiler for performance analysis - AutoMapper for object mapping - AutoFac for dependency injection - CORS support - JWT custom policy authorization - Microservices support (Docker, Jenkins, Consul, Nacos, API Gateways, Nginx, Ids4) ``` -------------------------------- ### Database and ORM Technologies Source: https://github.com/anjoy8/blog.core/blob/master/README-en.md Highlights the database technologies and ORM frameworks utilized, including SQL Server 2012, Sqlsugar for lightweight ORM with Codefirst approach, T4 templates for code generation, and AutoMapper for object mapping. ```APIDOC Database Technologies: - System Environment: Windows 10, SQL Server 2012, Visual Studio 2017, Windows Server R2. - Sqlsugar: Lightweight ORM Framework supporting Codefirst. - T4 Template generation: For generating code. - AutoMapper: Automatic Object mapping. ``` -------------------------------- ### Framework Module Features Source: https://github.com/anjoy8/blog.core/blob/master/README.md Details the functionalities and components included in the framework module of Blog.Core. This covers the core architectural patterns, database interactions, and development utilities. ```APIDOC Framework Module: - Encapsulation using Repository + Service + Interface pattern. - Custom project template 'CreateYourProject.bat' for quick project setup. - Asynchronous development with async/await. - SqlSugar ORM for database operations, supporting cascading operations. - Database switching support (MySql, SqlServer, Sqlite, Oracle, Postgresql, etc.). - Automatic seed data generation on project startup. - Configurable database primary key types. - Five types of logging (Audit, Exception, Request/Response, Service Operation, SQL) persisted to database. - Transaction handling (supports distributed transactions with CAP). - Four types of AOP (Aspect-Oriented Programming): logging, caching, auditing, transactions. - Global Serilog logging integrated with native ILogger interface, persisting logs to database. - Button-level RBAC permission control with one-click synchronization of interfaces and menus. - T4 code template support for automatic code generation. - DbFirst for one-click creation of project layers (supports multiple databases). - 'Blog.Core.Webapi.Template' project template for rebuilding projects. - Multiple frontend examples provided (Blog.Vue, Blog.Admin, Nuxt.tbug, Blog.Mvp.Blazor). - Integrated IdentityServer4 for authentication. - Multi-tenancy implementation. - Table partitioning example (SplitDemoController.cs). - SignalR support for targeted user communication. ``` -------------------------------- ### Generate Multi-Layer Framework Files Source: https://github.com/anjoy8/blog.core/wiki/Framework This C# method in `DbFirstController` triggers the automatic generation of multi-layer framework files (models, repositories, services) based on database schema. It relies on the `FrameSeed` class and `MyContext` for database operations. ```csharp private readonly MyContext myContext; /// /// 构造函数 /// /// public DbFirstController(MyContext myContext) { this.myContext = myContext; } /// /// 获取 整体框架 文件 /// /// [HttpGet] public bool GetFrameFiles() { return FrameSeed.CreateModels(myContext) && FrameSeed.CreateIRepositorys(myContext) && FrameSeed.CreateIServices(myContext) && FrameSeed.CreateRepository(myContext) && FrameSeed.CreateServices(myContext) ; ``` -------------------------------- ### .NET Core Backend Technologies Source: https://github.com/anjoy8/blog.core/blob/master/README-en.md Details the backend technology stack for the .NET Core 2.0 API project, emphasizing a clean architecture with Repository + Service pattern, asynchronous programming, cross-domain solutions, AOP, dependency injection, and JWT authentication. ```APIDOC Backend Technology Stack: - .NET Core 2.0 API: Used for building front and rear separation with a RESTful style. - Swagger: For API documentation and description. - Repository + Service Warehousing mode: Programming pattern for data access and business logic. - Async and await: For asynchronous programming. - Cors: Simple cross-domain solution. - AOP (Aspect-Oriented Programming): Based on tangent programming technology. - AUTOFAC: Lightweight IOC and DI (Dependency Injection) container. - Vue Local Agent / Nginx: Used for cross-domain scenarios and proxying. - JWT Permission Authentication: For securing APIs. ``` -------------------------------- ### Frontend Technology Stack Source: https://github.com/anjoy8/blog.core/blob/master/README-en.md Details the frontend technology stack, primarily based on Vue.js 2.0 ecosystem, including Vue Router, Webpack, Axios, Vue CLI, Vuex, Element-UI component library, and Nuxt.js for server-side rendering. ```APIDOC Frontend Technology Stack: - Vue 2.0 Framework Family: Vue2, VueRouter2, Webpack, Axios, vue-cli, Vuex. - Element-ui: Component library based on Vue 2.0. - Nuxt.js: Server Render (SSR) framework. ``` -------------------------------- ### Component Module Features Source: https://github.com/anjoy8/blog.core/blob/master/README.md Lists the integrated components and libraries used within the Blog.Core framework. These components enhance functionality such as caching, API documentation, performance monitoring, and dependency injection. ```APIDOC Component Module: - Redis for caching. - Swagger for API documentation. - MiniProfiler for API performance analysis. - AutoMapper for object mapping. - AutoFac for dependency injection container with batch service injection. - CORS cross-origin support. - JWT custom policy authorization. - Serilog logging framework integrated with native ILogger. - SignalR for duplex communication. - IpRateLimiting for API throttling. - Quartz.NET for task scheduling (single-machine multi-task, cluster scheduling not yet supported). - Database read/write separation and multi-database operations. - Redis Message Queue. - RabbitMQ Message Queue. - EventBus implementation. - Unified payment aggregation. - Nacos service discovery configuration. - ES search configuration. - Apollo configuration. - Kafka Message Queue, used with EventBus. - WeChat Official Account management integrated into Blog.Admin. - Data department permissions. - Serilog integration for persisting logs to database. - Multi-tenancy modes (single table, multiple tables, multiple databases). - SnowflakeId.AutoRegister for automatic registration of Snowflake ID WorkerId, supporting distributed deployment. ``` -------------------------------- ### Related Front-end Projects Source: https://github.com/anjoy8/blog.core/wiki/Home Lists the companion front-end projects developed for the Blog.Core backend. These projects provide the user interfaces for the blog platform. ```APIDOC Front-end Projects: - Blog.Vue: https://github.com/anjoy8/Blog.Vue - Blog.Admin: https://github.com/anjoy8/Blog.Admin - Nuxt.tibug: https://github.com/anjoy8/Nuxt.tBug ``` -------------------------------- ### Autofac Service Registration for AOP Source: https://github.com/anjoy8/blog.core/wiki/AOP Demonstrates how to register AOP services (BlogCacheAOP, BlogRedisCacheAOP, BlogLogAOP) using Autofac in Startup.cs. It shows conditional registration based on appsettings.json and applying multiple interceptors to services. ```csharp // Registering individual AOP types (example) builder.RegisterType(); builder.RegisterType(); builder.RegisterType(); // Conditional registration and applying multiple interceptors var cacheType = new List(); if (Appsettings.app(new string[] { "AppSettings", "RedisCaching", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(BlogRedisCacheAOP)); } if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(BlogCacheAOP)); } if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(BlogLogAOP)); } builder.RegisterAssemblyTypes(assemblysServices) .AsImplementedInterfaces() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() .InterceptedBy(cacheType.ToArray()); ``` -------------------------------- ### Configure Multiple Database Connection Strings Source: https://github.com/anjoy8/blog.core/wiki/support-muti-db Defines the connection details for various databases. Each entry requires a unique 'ConnId', a 'DBType' (e.g., 0 for MySQL, 1 for SQLServer, 2 for SQLite, 3 for Oracle, 4 for PostgreSQL), an 'Enabled' flag, and the 'Connection' string. The 'ProviderName' is optional but recommended for specific database types like SQL Server. ```json { "DBS": [ { "ConnId": "WMBLOG_SQLITE", "DBType": 2, "Enabled": true, "Connection": "WMBlog.db" }, { "ConnId": "WMBLOG_MSSQL", "DBType": 1, "Enabled": true, "Connection": "Server=.;Database=WMBlogDB;User ID=sa;Password=123;", "ProviderName": "System.Data.SqlClient" }, { "ConnId": "WMBLOG_MYSQL", "DBType": 0, "Enabled": true, "Connection": "Server=localhost; Port=3306;Stmt=; Database=wmblogdb; Uid=root; Pwd=456;" }, { "ConnId": "WMBLOG_ORACLE", "DBType": 3, "Enabled": false, "Connection": "Provider=OraOLEDB.Oracle; Data Source=WMBlogDB; User Id=sss; Password=789;", "OracleConnection_other1": "User ID=sss;Password=789;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.8.65)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME = orcl)))" } ] } ``` -------------------------------- ### JavaScript Login Form Submission Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/wwwroot/swg-login.html Provides functionality to submit login credentials via AJAX to a backend API. It includes a helper function to retrieve URL query parameters and validates input before sending the request. ```javascript function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=(\[^&]\*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; } function submit() { let postdata = { "name": $("#email").val(), "pwd": $("#password").val(), }; if (!(postdata.name && postdata.pwd)) { alert('参数不正确'); return; } $.ajax({ url: "/api/Login/swgLogin", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: 'json', success: function (data) { if (data?.result) { var returnUrl = GetQueryString("returnUrl"); if (returnUrl != null && returnUrl.length > 0) { window.location.href = returnUrl; } else { window.location.href = "/index.html"; } } else { alert('参数不正确'); } } }); } ``` -------------------------------- ### Program.cs: Initialize Log4net Repository Source: https://github.com/anjoy8/blog.core/wiki/Log4Net-日志集成到-ILogger This C# code snippet demonstrates how to load the Log4net configuration and initialize the logging repository within the Program.cs file of a .NET Core application. ```csharp using System.IO; using System.Reflection; using System.Xml; using log4net; using log4net.Config; // ... inside Main or ConfigureServices ... XmlDocument log4netConfig = new XmlDocument(); log4netConfig.Load(File.OpenRead("Log4net.config")); // Ensure Log4net.config is in the correct path var repo = LogManager.CreateRepository( Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); XmlConfigurator.Configure(repo, log4netConfig["log4net"]); ``` -------------------------------- ### Enterprise Use Advanced Version Features Source: https://github.com/anjoy8/blog.core/blob/master/README.md Highlights the additional features and improvements available in the advanced enterprise version of Blog.Core, focusing on enhanced data permissions, distributed scenarios, and user management. ```APIDOC Enterprise Use Advanced Version: - Includes all features from the open-source framework/component modules. - All table structure primary keys changed to 'string' type (default Snowflake, supports GUID) for easier migration. - Enhanced department data permissions with policy-based data scope configuration. - Optimized permission processor to resolve permission synchronization issues in multi-instance distributed environments (requires Redis configuration). - Added online user viewing and forced user logout functionality (requires Redis configuration). - Added user blacklist functionality (requires Redis configuration). - Added position functionality (separate table) for use with departments. - Future optimization for in-site notification functionality (currently uses SignalR for message push). - Frontend 'Blog.Admin.Pro' to use AntDesignVue framework (design in progress, not fully implemented). - Loyalty reward: Half-price commercial authorization for participation in development of the above features and other paid features. ``` -------------------------------- ### Configure Authentication and Authorization Middleware Source: https://github.com/anjoy8/blog.core/wiki/Authorization-JWT Adds the necessary middleware to the application pipeline to handle authentication and authorization requests. This enables the security features configured earlier. ```csharp app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); ``` -------------------------------- ### Distributed Caching Technology Source: https://github.com/anjoy8/blog.core/blob/master/README-en.md Specifies the use of Redis as a lightweight distributed caching solution within the project architecture. ```APIDOC Distributed Caching: - Redis: Lightweight Distributed cache. ``` -------------------------------- ### Inject IUser in Constructor Source: https://github.com/anjoy8/blog.core/wiki/UserInfo Demonstrates injecting the IUser interface into a controller's constructor for dependency injection. This is a common pattern for accessing services within application components. ```csharp private readonly IUser _user; public ModuleController(IModuleServices moduleServices, IUser user) { _moduleServices = moduleServices; _user = user; } ``` -------------------------------- ### Swagger UI Customizations and Enhancements Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/index.html Applies various UI customizations after the Swagger UI has loaded. This includes adding a QR code and links to related services, translating UI elements like authorization button text, and modifying the appearance of lock icons for authentication status. ```javascript setTimeout(() => { // QR code $('.info').append("
"); // Modify token authorization button to Chinese $(".auth-wrapper span").empty(); $(document).ready(function () { $(".auth-wrapper span").each(function () { var myvalue = '授权认证(JWT已自动授权)'; $(this).html(myvalue); }); }); // Modify permission lock style, directly modifying style as this single page does not fetch token $(document).ready(function () { setTimeout(() => { document.querySelector('.auth-wrapper svg use').href.baseVal = '#locked'; let divList = document.querySelectorAll('.opblock-tag'); for (let div of divList) { div.addEventListener('click', function () { setTimeout(() => { // Modify lock status: locked to authenticated token, unlocked to unauthenticated token let list = document.querySelectorAll('.unlocked svg use'); for (let item of list) { item.href.baseVal = '#locked'; } // Modify lock color: locked black, unlocked gray let btnlist = document.querySelectorAll('.authorization__btn'); for (let item of btnlist) { item.classList = 'authorization__btn locked'; } }, 0); }); } }, 500); }); }, 1000); // Document logo $(".link img").attr("src", "./logo/favicon-32x32.png"); ``` -------------------------------- ### Blog.Core API Address Source: https://github.com/anjoy8/blog.core/wiki/Home Provides the base URL for accessing the Blog.Core project's API services. This is the primary endpoint for interacting with the backend functionality. ```APIDOC API Address: http://apk.neters.club ``` -------------------------------- ### Configure JWT Authentication and Authorization Source: https://github.com/anjoy8/blog.core/wiki/Authorization-JWT Sets up JWT Bearer authentication and custom role-based authorization policies. Includes defining signing keys, validation parameters, and permission requirements for API security. ```csharp var audienceConfig = Configuration.GetSection("Audience"); var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String; var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var permission = new List(); var permissionRequirement = new PermissionRequirement( "/api/denied", permission, ClaimTypes.Role, audienceConfig["Issuer"], audienceConfig["Audience"], signingCredentials, expiration: TimeSpan.FromSeconds(60 * 60) ); services.AddAuthorization(options => { options.AddPolicy(Permissions.Name, policy => policy.Requirements.Add(permissionRequirement)); }); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = audienceConfig["Issuer"], ValidateAudience = true, ValidAudience = audienceConfig["Audience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(30), RequireExpirationTime = true, }; services.AddAuthentication("Bearer") .AddJwtBearer(o => { o.TokenValidationParameters = tokenValidationParameters; o.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return Task.CompletedTask; } }; }); services.AddSingleton(); services.AddSingleton(permissionRequirement); ``` -------------------------------- ### Blog.Core API Controllers Source: https://github.com/anjoy8/blog.core/blob/master/README.md Lists the primary API controllers within the Blog.Core project, which are crucial for its RBAC-based, button-level role authorization logic. These controllers manage core functionalities. ```APIDOC API Controllers: - BaseApiController.cs (Base API Controller) - DepartmentController (Department Management) - ImgController (Image Handling) - LoginController (User Authentication) - ModuleController (Interface/Module Management) - PermissionController (Menu/Permission Management) - RoleController (Role Management) - TasksQzController (Task Scheduling) - UserController (User Management) - UserRoleController (User-Role Relationship Management) Description: These controllers form the API layer and implement RBAC authorization. They are essential for the project's security and functionality. Extended business logic controllers can be removed if not needed. ``` -------------------------------- ### Add MyContext to Dependency Injection Source: https://github.com/anjoy8/blog.core/wiki/Framework Configures the application's dependency injection container to scope the `MyContext` service. This makes the database context available for injection into controllers and other services. ```csharp services.AddScoped(); ``` -------------------------------- ### Register IUser Service Source: https://github.com/anjoy8/blog.core/wiki/UserInfo Registers the AspNetUser implementation of the IUser interface as a scoped service in the dependency injection container. This makes the user information service available throughout the application's request lifecycle. ```csharp services.AddScoped(); ``` -------------------------------- ### JavaScript Input Focus Animations Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/wwwroot/swg-login.html Handles focus events on input fields ('#email', '#password', '#submit') to trigger visual animations using the anime.js library. It manages animation states to ensure only one animation runs at a time. ```javascript var current = null; document.querySelector('#email').addEventListener('focus', function (e) { if (current) current.pause(); current = anime({ targets: 'path', strokeDashoffset: { value: 0, duration: 700, easing: 'easeOutQuart' }, strokeDasharray: { value: '240 1386', duration: 700, easing: 'easeOutQuart' } }); }); document.querySelector('#password').addEventListener('focus', function (e) { if (current) current.pause(); current = anime({ targets: 'path', strokeDashoffset: { value: -336, duration: 700, easing: 'easeOutQuart' }, strokeDasharray: { value: '240 1386', duration: 700, easing: 'easeOutQuart' } }); }); document.querySelector('#submit').addEventListener('focus', function (e) { if (current) current.pause(); current = anime({ targets: 'path', strokeDashoffset: { value: -730, duration: 700, easing: 'easeOutQuart' }, strokeDasharray: { value: '530 1386', duration: 700, easing: 'easeOutQuart' } }); }); ``` -------------------------------- ### Enable Multi-Database Operations Source: https://github.com/anjoy8/blog.core/wiki/support-muti-db Enables the application to connect to and manage multiple databases simultaneously. This setting must be set to 'true' in the application's configuration file (e.g., appsettings.json) to activate multi-database functionality. ```json { "MutiDBEnabled": true } ``` -------------------------------- ### Blog.Core Project Core Layers Source: https://github.com/anjoy8/blog.core/blob/master/README.md Identifies the essential layers of the Blog.Core project that form its core architecture and should not be removed. These layers support the project's functionality. ```APIDOC Core Layers: - Blog.Core.Api - Blog.Core.Common - Blog.Core.IServices - Blog.Core.Model - Blog.Core.Repository - Blog.Core.Services - Blog.Core.Tasks - Blog.Core.Serilog Description: These are the fundamental layers of the Blog.Core framework. Other layers are considered supporting and can be removed if not required by specific business logic. ``` -------------------------------- ### Configure Main Database ID Source: https://github.com/anjoy8/blog.core/wiki/support-muti-db Specifies the connection ID of the primary database for the project. This 'ConnId' must correspond to an entry in the 'DBS' configuration that has 'Enabled' set to 'true'. All operations not explicitly directed to another database will default to this main database. ```json { "MainDB": "WMBLOG_SQLITE" } ``` -------------------------------- ### Browser Compatibility Check (Edge) Source: https://github.com/anjoy8/blog.core/blob/master/Blog.Core.Api/index.html Checks if the user agent is Microsoft Edge and removes native fetch if detected, favoring Swagger UI's polyfill. ```javascript if (window.navigator.userAgent.indexOf("Edge") > -1) { console.log("Removing native Edge fetch in favor of swagger-ui's polyfill"); window.fetch = undefined; } ``` -------------------------------- ### Appsettings.json AOP Configuration Source: https://github.com/anjoy8/blog.core/wiki/AOP Configuration settings in appsettings.json to enable or disable specific AOP features like Redis caching, memory caching, and logging. These settings control the runtime behavior of the AOP components. ```json { "RedisCaching": { "Enabled": false, "ConnectionString": "127.0.0.1:6319" }, "MemoryCachingAOP": { "Enabled": true }, "LogAOP": { "Enabled": true } } ``` -------------------------------- ### Map Entity Models to Database Connections Source: https://github.com/anjoy8/blog.core/wiki/support-muti-db Associates entity classes with specific database connections using the 'SugarTable' attribute. The first parameter is the table name, and the second parameter is the 'ConnId' from the 'DBS' configuration. If this attribute is omitted, the entity will default to using the 'MainDB' connection. ```csharp using SqlSugar; // ... [SugarTable("PasswordLib", "WMBLOG_MSSQL")] public class PasswordLib { [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = true)] public int PLID { get; set; } // more properties... } ``` -------------------------------- ### API Controller with Authorization Source: https://github.com/anjoy8/blog.core/wiki/Authorization-JWT Applies a custom authorization policy named 'Permissions.Name' to an API controller. This ensures that only requests meeting the criteria defined in the policy can access the controller's actions. ```csharp /// /// 接口管理 /// [Route("api/[controller]/[action]")] [ApiController] [Authorize(Permissions.Name)] public class ModuleController : ControllerBase ``` -------------------------------- ### Configure Middleware: Add Log4netProvider Source: https://github.com/anjoy8/blog.core/wiki/Log4Net-日志集成到-ILogger This C# code shows how to integrate Log4net into the ASP.NET Core logging pipeline by adding a custom Log4NetProvider to the ILoggerFactory in the Configure method. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using log4net.Provider; public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Add Log4netProvider to the logging pipeline loggerFactory.AddProvider(new Log4NetProvider("Log4net.config")); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` -------------------------------- ### Log4net Configuration (XML) Source: https://github.com/anjoy8/blog.core/wiki/Log4Net-日志集成到-ILogger This XML file configures the Log4net framework, specifying appenders for rolling file output based on date, layout patterns, and root logging levels. ```xml ``` -------------------------------- ### Custom Permission Authorization Handler Source: https://github.com/anjoy8/blog.core/wiki/Authorization-JWT Defines a custom authorization handler class, PermissionHandler, which inherits from AuthorizationHandler. This class is intended to implement the logic for evaluating custom authorization policies. ```csharp /// /// 权限授权处理器 /// public class PermissionHandler : AuthorizationHandler { } ``` -------------------------------- ### Controller: Inject and Use ILogger Source: https://github.com/anjoy8/blog.core/wiki/Log4Net-日志集成到-ILogger This C# snippet demonstrates how to inject the ILogger interface into a controller and use it to log messages, such as an error message. ```csharp using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; public class WeatherForecastController : ControllerBase { private readonly ILogger _logger; public WeatherForecastController(ILogger logger) { _logger = logger; } [HttpGet] public IEnumerable Get() { _logger.LogError("This is an error message from WeatherForecastController."); var rng = new Random(); // Placeholder for actual data generation return null; } } // Assuming WeatherForecast class is defined elsewhere ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.