├── .gitignore ├── JwtTokenDemo ├── Common │ ├── AppSettings.cs │ └── Jwt.cs ├── Controllers │ └── StudentController.cs ├── Core.csproj ├── Core.sln ├── Extensions │ └── ObjectExtensions.cs ├── Models │ ├── Response.cs │ └── Student.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Log4netDemo ├── Controllers │ └── StudentController.cs ├── Core.csproj ├── Core.sln ├── Extensions │ └── ObjectExtensions.cs ├── Filters │ └── ApiLogFilter.cs ├── Log │ ├── Api │ │ └── 20200718.log │ └── Error │ │ └── 20200718.log ├── Middlewares │ └── ExceptionMiddleware.cs ├── Models │ ├── Response.cs │ └── Student.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json ├── appsettings.json └── log4net.config ├── README.md └── RepositoryDemo ├── Core.Common ├── AppSettings.cs ├── Core.Common.csproj └── JsonHelper.cs ├── Core.IRepository ├── Core.IRepository.csproj ├── IBaseRepository.cs ├── IStudentRepository.cs ├── ITeacherRepository.cs └── IUnitOfWork.cs ├── Core.IService ├── Core.IService.csproj ├── IBaseService.cs ├── IStudentService.cs └── ITeacherService.cs ├── Core.Model ├── Core.Model.csproj ├── Core.Model.csproj.user ├── Migrations │ ├── 20200718085404_init.Designer.cs │ ├── 20200718085404_init.cs │ └── MyDbContextModelSnapshot.cs ├── MySqlContext.cs ├── Response.cs └── School │ ├── Course.cs │ ├── Sc.cs │ ├── Student.cs │ └── Teacher.cs ├── Core.Repository ├── BaseRepository.cs ├── Core.Repository.csproj ├── StudentRepository.cs ├── TeacherRepository.cs └── UnitOfWork.cs ├── Core.Service ├── BaseService.cs ├── Core.Service.csproj ├── StudentService.cs └── TeacherService.cs ├── Core.sln └── Core ├── Controllers └── StudentController.cs ├── Core.csproj ├── Core.csproj.user ├── Core.xml ├── Model.xml ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json /.gitignore: -------------------------------------------------------------------------------- 1 | .vs 2 | bin 3 | obj 4 | -------------------------------------------------------------------------------- /JwtTokenDemo/Common/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using System; 3 | using System.IO; 4 | 5 | namespace Core 6 | { 7 | public class AppSettings 8 | { 9 | private static readonly IConfigurationRoot configuration; 10 | 11 | static AppSettings() 12 | { 13 | configuration = new ConfigurationBuilder() 14 | .SetBasePath(Directory.GetCurrentDirectory()) 15 | .AddJsonFile("appsettings.json", false, true) 16 | .Build(); 17 | } 18 | 19 | public static class JWT 20 | { 21 | public static string Issuer => configuration["JWT:Issuer"]; 22 | public static string AccessTokenAudience => configuration["JWT:AccessTokenAudience"]; 23 | public static int AccessTokenExpires => Convert.ToInt32(configuration["JWT:AccessTokenExpires"]); 24 | public static string RefreshTokenAudience => configuration["JWT:RefreshTokenAudience"]; 25 | public static int RefreshTokenExpires => Convert.ToInt32(configuration["JWT:RefreshTokenExpires"]); 26 | public static string SecurityKey => configuration["JWT:SecurityKey"]; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Common/Jwt.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.Tokens; 2 | using System; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Security.Claims; 5 | using System.Text; 6 | 7 | namespace Core 8 | { 9 | public class Jwt 10 | { 11 | public static string CreateToken(Student student, TokenType type) 12 | { 13 | var audience = type == TokenType.AccessToken ? AppSettings.JWT.AccessTokenAudience : AppSettings.JWT.RefreshTokenAudience; 14 | 15 | var expires = type == TokenType.AccessToken ? AppSettings.JWT.AccessTokenExpires : AppSettings.JWT.RefreshTokenExpires; 16 | 17 | var claims = new Claim[] { 18 | new Claim(ClaimTypes.Name, student.Account), 19 | new Claim(JwtRegisteredClaimNames.Iss,AppSettings.JWT.Issuer), 20 | new Claim(JwtRegisteredClaimNames.Aud,audience), 21 | new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), 22 | new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(expires)).ToUnixTimeSeconds()}") 23 | }; 24 | 25 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT.SecurityKey)); 26 | var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 27 | 28 | var securityToken = new JwtSecurityToken( 29 | issuer: AppSettings.JWT.Issuer, 30 | audience: audience, 31 | claims: claims, 32 | expires: DateTime.Now.AddSeconds(expires), 33 | signingCredentials: signingCredentials); 34 | 35 | return "Bearer " + new JwtSecurityTokenHandler().WriteToken(securityToken); 36 | } 37 | 38 | public static bool ValidateRefreshToken(string refreshToken, out Student student) 39 | { 40 | var tokenValidationParameters = new TokenValidationParameters 41 | { 42 | ValidateIssuer = true, 43 | ValidIssuer = AppSettings.JWT.Issuer, 44 | ValidateAudience = true, 45 | ValidAudience = AppSettings.JWT.RefreshTokenAudience, 46 | ValidateLifetime = true, 47 | ClockSkew = TimeSpan.FromSeconds(0), 48 | ValidateIssuerSigningKey = true, 49 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT.SecurityKey)) 50 | }; 51 | 52 | var tokenHandler = new JwtSecurityTokenHandler(); 53 | 54 | SecurityToken securityToken; 55 | 56 | try 57 | { 58 | tokenHandler.ValidateToken(refreshToken, tokenValidationParameters, out securityToken); 59 | student = SerializeToken(securityToken); 60 | 61 | return true; 62 | } 63 | catch (Exception) 64 | { 65 | student = null; 66 | return false; 67 | } 68 | } 69 | 70 | public static Student SerializeToken(SecurityToken securityToken) 71 | { 72 | Student student = new Student(); 73 | 74 | object account; 75 | 76 | (securityToken as JwtSecurityToken).Payload.TryGetValue(ClaimTypes.Name, out account); 77 | 78 | student.Account = account.ToString(); 79 | 80 | return student; 81 | } 82 | } 83 | 84 | public enum TokenType 85 | { 86 | AccessToken, 87 | RefreshToken 88 | } 89 | 90 | public class JwtDto 91 | { 92 | public string AccessToken { get; set; } 93 | public string RefreshToken { get; set; } 94 | } 95 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Controllers/StudentController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Core.Controllers 7 | { 8 | [ApiController] 9 | [Route("api/[controller]/[action]")] 10 | public class StudentController : ControllerBase 11 | { 12 | public static readonly List students = new List() 13 | { 14 | new Student(){Account="1001", Password="123456", Name="张三",Sex="男",Age=25 }, 15 | new Student(){Account="1002", Password="123456", Name="李四",Sex="男",Age=24 }, 16 | new Student(){Account="1003", Password="123456", Name="王五",Sex="男",Age=23 } 17 | }; 18 | 19 | [HttpGet] 20 | public Response Login(string account, string password) 21 | { 22 | var response = new Response(); 23 | 24 | var user = students.SingleOrDefault(t => t.Account == account); 25 | 26 | if (user != null) 27 | { 28 | if (user.Password.Equals(password)) 29 | { 30 | response.Msg = "登录成功"; 31 | 32 | var token = new JwtDto() 33 | { 34 | AccessToken = Jwt.CreateToken(user, TokenType.AccessToken), 35 | RefreshToken = Jwt.CreateToken(user, TokenType.RefreshToken) 36 | }; 37 | 38 | response.Data = token; 39 | } 40 | else 41 | { 42 | response.Status = 400; 43 | response.Msg = "用户密码不正确!"; 44 | } 45 | } 46 | else 47 | { 48 | response.Status = 400; 49 | response.Msg = "用户名不存在!"; 50 | } 51 | 52 | return response; 53 | } 54 | 55 | [HttpGet] 56 | public Response RefreshToken(string refreshToken) 57 | { 58 | Student student; 59 | var response = new Response(); 60 | 61 | if (Jwt.ValidateRefreshToken(refreshToken.ToStringX().Replace("Bearer ", ""), out student)) 62 | { 63 | response.Data = Jwt.CreateToken(student, TokenType.AccessToken); 64 | } 65 | else 66 | { 67 | response.Status = 401; 68 | response.Msg = "Unauthorized"; 69 | } 70 | 71 | return response; 72 | } 73 | 74 | [HttpGet] 75 | [Authorize] 76 | public Response JwtTokenTest() 77 | { 78 | var result = new Response(); 79 | 80 | return result; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /JwtTokenDemo/Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /JwtTokenDemo/Core.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "Core.csproj", "{3E6E7C43-692E-45B1-9150-937E13400070}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {3E6E7C43-692E-45B1-9150-937E13400070}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {3E6E7C43-692E-45B1-9150-937E13400070}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {3E6E7C43-692E-45B1-9150-937E13400070}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {3E6E7C43-692E-45B1-9150-937E13400070}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {8EC3DE09-1AA7-4BFA-B8C6-2C3C5C87E490} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /JwtTokenDemo/Extensions/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Serialization; 3 | 4 | namespace Core 5 | { 6 | public static class ObjectExtensions 7 | { 8 | public static string ToJson(this object obj) 9 | { 10 | var serializerSettings = new JsonSerializerSettings 11 | { 12 | DateFormatString = "yyyy-MM-dd HH:mm:ss", 13 | ContractResolver = new CamelCasePropertyNamesContractResolver() 14 | }; 15 | 16 | return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings); 17 | } 18 | 19 | public static string ToStringX(this object obj) 20 | { 21 | return obj == null ? "" : obj.ToString(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Models/Response.cs: -------------------------------------------------------------------------------- 1 | namespace Core 2 | { 3 | public class Response 4 | { 5 | public int Status { get; set; } = 200; 6 | 7 | public string Msg { get; set; } = "操作成功!"; 8 | 9 | public T Data { get; set; } 10 | 11 | public void Success(T data, string msg = "") 12 | { 13 | this.Status = 200; 14 | this.Msg = msg; 15 | this.Data = data; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Models/Student.cs: -------------------------------------------------------------------------------- 1 | namespace Core 2 | { 3 | public class Student 4 | { 5 | public string Account { get; set; } 6 | public string Password { get; set; } 7 | public string Name { get; set; } 8 | public int Age { get; set; } 9 | public string Sex { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace Core 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:59961", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Core": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "applicationUrl": "http://localhost:5000", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /JwtTokenDemo/Startup.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangxiufei/Samples/6ea4d5f62da7c84ec6359c42b5505b5eaf0c0923/JwtTokenDemo/Startup.cs -------------------------------------------------------------------------------- /JwtTokenDemo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JwtTokenDemo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "JWT": { 11 | "Issuer": ".Net Core Api", 12 | "AccessTokenAudience": "AccessToken Client", 13 | "AccessTokenExpires": 1200, 14 | "RefreshTokenAudience": "RefreshToken Client", 15 | "RefreshTokenExpires": 86400, 16 | "SecurityKey": "5bGx5LicLea1juWugS3msbbkuIrljr8t5ZCR5L+u6aOe" 17 | } 18 | } -------------------------------------------------------------------------------- /Log4netDemo/Controllers/StudentController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Core.Controllers 6 | { 7 | [ApiController] 8 | [Route("api/[controller]")] 9 | public class StudentController : ControllerBase 10 | { 11 | public static readonly List students = new List() 12 | { 13 | new Student(){Id=1, Name="张三",Sex="男",Age=25 }, 14 | new Student(){Id=2, Name="李四",Sex="男",Age=24 }, 15 | new Student(){Id=3, Name="王五",Sex="男",Age=23 } 16 | }; 17 | 18 | [HttpGet("{id}")] 19 | public Response> GetStudent([FromRoute] int id) 20 | { 21 | var response = new Response>(); 22 | 23 | response.data = students.Where(t => t.Id == id).ToList(); 24 | 25 | return response; 26 | } 27 | 28 | [HttpGet] 29 | public Response> GetStudentList() 30 | { 31 | var response = new Response>(); 32 | 33 | response.data = students; 34 | 35 | return response; 36 | } 37 | 38 | [HttpPost] 39 | public Response InsertStudent([FromBody] Student student) 40 | { 41 | students.Add(student); 42 | 43 | return new Response(); 44 | } 45 | 46 | [HttpPut("{id}")] 47 | public Response UpdateStudent([FromRoute]int id, [FromBody] Student student) 48 | { 49 | for (int i = 0; i < students.Count; i++) 50 | { 51 | if (students[i].Id == id) 52 | { 53 | students[i].Name = student.Name; 54 | students[i].Sex = student.Sex; 55 | students[i].Age = student.Age; 56 | } 57 | } 58 | 59 | return new Response(); 60 | } 61 | 62 | [HttpDelete("{id}")] 63 | public Response DeleteStudent([FromRoute]int id) 64 | { 65 | for (int i = 0; i < students.Count; i++) 66 | { 67 | if (students[i].Id == id) 68 | { 69 | students.RemoveAt(i); 70 | } 71 | } 72 | 73 | return new Response(); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /Log4netDemo/Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Log4netDemo/Core.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "Core.csproj", "{3E6E7C43-692E-45B1-9150-937E13400070}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {3E6E7C43-692E-45B1-9150-937E13400070}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {3E6E7C43-692E-45B1-9150-937E13400070}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {3E6E7C43-692E-45B1-9150-937E13400070}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {3E6E7C43-692E-45B1-9150-937E13400070}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {8EC3DE09-1AA7-4BFA-B8C6-2C3C5C87E490} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Log4netDemo/Extensions/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Serialization; 3 | 4 | namespace Core 5 | { 6 | public static class ObjectExtensions 7 | { 8 | public static string ToJson(this object obj) 9 | { 10 | var serializerSettings = new JsonSerializerSettings 11 | { 12 | DateFormatString = "yyyy-MM-dd HH:mm:ss", 13 | ContractResolver = new CamelCasePropertyNamesContractResolver() 14 | }; 15 | 16 | return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Log4netDemo/Filters/ApiLogFilter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Filters; 2 | using Microsoft.Extensions.Logging; 3 | using System.Threading.Tasks; 4 | using System.Diagnostics; 5 | using Newtonsoft.Json; 6 | 7 | namespace Core 8 | { 9 | public class ApiLogFilter : IAsyncActionFilter 10 | { 11 | private readonly ILogger logger; 12 | 13 | public ApiLogFilter(ILogger logger) 14 | { 15 | this.logger = logger; 16 | } 17 | 18 | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 19 | { 20 | string actionArguments = context.ActionArguments.ToJson(); 21 | 22 | var resultContext = await next(); 23 | 24 | string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString; 25 | 26 | string method = resultContext.HttpContext.Request.Method; 27 | 28 | dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic; 29 | 30 | string response = JsonConvert.SerializeObject(result.Value); 31 | 32 | logger.LogInformation($"URL:{url} \n " + 33 | $"Method:{method} \n " + 34 | $"ActionArguments:{actionArguments}\n " + 35 | $"Response:{response}\n "); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Log4netDemo/Log/Api/20200718.log: -------------------------------------------------------------------------------- 1 | 【记录时间】2020-07-18 22:40:10,795 2 | 【详细内容】URL:localhost:59961/api/Student/1 3 | Method:GET 4 | ActionArguments:{"id":1} 5 | Response:{"status":200,"msg":"操作成功!","data":[{"Id":1,"Name":"张三","Age":25,"Sex":"男"}]} 6 | 7 | 【记录时间】2020-07-18 22:40:45,619 8 | 【详细内容】URL:localhost:59961/api/Student 9 | Method:POST 10 | ActionArguments:{"student":{"id":4,"name":"马六","age":22,"sex":"男"}} 11 | Response:{"status":200,"msg":"操作成功!","data":null} 12 | 13 | 【记录时间】2020-07-18 22:41:36,421 14 | 【详细内容】URL:localhost:59961/api/Student/2 15 | Method:PUT 16 | ActionArguments:{"id":2,"student":{"id":2,"name":"李四","age":30,"sex":"男"}} 17 | Response:{"status":200,"msg":"操作成功!","data":null} 18 | 19 | 【记录时间】2020-07-18 22:41:49,284 20 | 【详细内容】URL:localhost:59961/api/Student/3 21 | Method:DELETE 22 | ActionArguments:{"id":3} 23 | Response:{"status":200,"msg":"操作成功!","data":null} 24 | 25 | -------------------------------------------------------------------------------- /Log4netDemo/Log/Error/20200718.log: -------------------------------------------------------------------------------- 1 | 2 | 【记录时间】2020-07-18 22:20:57,382 3 | 【出错的类】/api/Student/1 4 | 【错误详情】 5 | System.NullReferenceException: Object reference not set to an instance of an object. 6 | at Core.ApiLogFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) in F:\Demo\Samples\Log4netDemo\Filters\ApiLogFilter.cs:line 28 7 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) 8 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) 9 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 10 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() 11 | --- End of stack trace from previous location where exception was thrown --- 12 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) 13 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) 14 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 15 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() 16 | --- End of stack trace from previous location where exception was thrown --- 17 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) 18 | at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 19 | at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 20 | at Core.ExceptionMiddleware.Invoke(HttpContext context) in F:\Demo\Samples\Log4netDemo\Middlewares\ExceptionMiddleware.cs:line 23 21 | 22 | 【记录时间】2020-07-18 22:39:36,215 23 | 【错误地址】/api/Student/1 24 | 【错误详情】 25 | System.NullReferenceException: Object reference not set to an instance of an object. 26 | at Core.ApiLogFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) in F:\Demo\Samples\Log4netDemo\Filters\ApiLogFilter.cs:line 28 27 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) 28 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) 29 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 30 | at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() 31 | --- End of stack trace from previous location where exception was thrown --- 32 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) 33 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) 34 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 35 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() 36 | --- End of stack trace from previous location where exception was thrown --- 37 | at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) 38 | at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 39 | at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 40 | at Core.ExceptionMiddleware.Invoke(HttpContext context) in F:\Demo\Samples\Log4netDemo\Middlewares\ExceptionMiddleware.cs:line 23 41 | -------------------------------------------------------------------------------- /Log4netDemo/Middlewares/ExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Threading.Tasks; 5 | 6 | namespace Core 7 | { 8 | public class ExceptionMiddleware 9 | { 10 | private readonly ILogger logger; 11 | private readonly RequestDelegate next; 12 | 13 | public ExceptionMiddleware(RequestDelegate next, ILogger logger) 14 | { 15 | this.logger = logger; 16 | this.next = next; 17 | } 18 | 19 | public async Task Invoke(HttpContext context) 20 | { 21 | try 22 | { 23 | await next(context); 24 | } 25 | catch (Exception e) 26 | { 27 | await ExceptionHandlerAsync(context, e); 28 | } 29 | } 30 | 31 | private async Task ExceptionHandlerAsync(HttpContext context, Exception e) 32 | { 33 | context.Response.ContentType = "application/json"; 34 | 35 | logger.LogError(e, context.Request.Path); 36 | 37 | var result = new Response() 38 | { 39 | status = 500, 40 | msg = e.Message 41 | }; 42 | 43 | await context.Response.WriteAsync(result.ToJson()); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /Log4netDemo/Models/Response.cs: -------------------------------------------------------------------------------- 1 | namespace Core 2 | { 3 | public class Response 4 | { 5 | public int status { get; set; } = 200; 6 | 7 | public string msg { get; set; } = "操作成功!"; 8 | 9 | public T data { get; set; } 10 | 11 | public void Success(T data, string msg = "") 12 | { 13 | this.status = 200; 14 | this.msg = msg; 15 | this.data = data; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Log4netDemo/Models/Student.cs: -------------------------------------------------------------------------------- 1 | namespace Core 2 | { 3 | public class Student 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | public int Age { get; set; } 8 | public string Sex { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /Log4netDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace Core 6 | { 7 | public class Program 8 | { 9 | public static void Main(string[] args) 10 | { 11 | CreateHostBuilder(args).Build().Run(); 12 | } 13 | 14 | public static IHostBuilder CreateHostBuilder(string[] args) => 15 | Host.CreateDefaultBuilder(args) 16 | .ConfigureLogging((context, loggingBuilder) => 17 | { 18 | loggingBuilder.AddFilter("System", LogLevel.Error); 19 | loggingBuilder.AddFilter("Microsoft", LogLevel.Error); 20 | loggingBuilder.AddLog4Net(); 21 | }) 22 | .ConfigureWebHostDefaults(webBuilder => 23 | { 24 | webBuilder.UseStartup(); 25 | }); 26 | } 27 | } -------------------------------------------------------------------------------- /Log4netDemo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:59961", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Core": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "applicationUrl": "http://localhost:5000", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Log4netDemo/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.OpenApi.Models; 7 | 8 | namespace Core 9 | { 10 | public class Startup 11 | { 12 | public Startup(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | 17 | public IConfiguration Configuration { get; } 18 | 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | services.AddControllers(); 22 | services.AddMvc(options => 23 | { 24 | options.Filters.Add(typeof(ApiLogFilter)); 25 | }); 26 | services.AddSwaggerGen(c => 27 | { 28 | c.SwaggerDoc("v1", new OpenApiInfo 29 | { 30 | Version = "v1", 31 | Title = "Core", 32 | }); 33 | }); 34 | } 35 | 36 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 37 | { 38 | if (env.IsDevelopment()) 39 | { 40 | app.UseDeveloperExceptionPage(); 41 | } 42 | 43 | app.UseSwagger(); 44 | app.UseSwaggerUI(c => 45 | { 46 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API V1"); 47 | c.RoutePrefix = ""; 48 | }); 49 | 50 | app.UseMiddleware(); 51 | 52 | app.UseRouting(); 53 | 54 | app.UseAuthorization(); 55 | 56 | app.UseEndpoints(endpoints => 57 | { 58 | endpoints.MapControllers(); 59 | }); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /Log4netDemo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Log4netDemo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /Log4netDemo/log4net.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .Net Core Samples 2 | 3 | ## 1. RepositoryDemo 4 | 5 | .net core 3.1 + swagger + autofac + ef core + 仓储模式 +工作单元 6 | 7 | ## 2. Log4netDemo 8 | 9 | .net core 3.1 + swagger + log4net + global exception log + api log 10 | 11 | ## 3. JwtTokenDemo 12 | 13 | .net core 3.1 + swagger + JWT AccessToken And RefreshToken 14 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Common/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.Configuration.Json; 3 | 4 | namespace Core.Common 5 | { 6 | public class AppSettings 7 | { 8 | public static IConfiguration Configuration { get; set; } 9 | 10 | static AppSettings() 11 | { 12 | Configuration = new ConfigurationBuilder() 13 | .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) 14 | .Build(); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Common/Core.Common.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Common/JsonHelper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | 4 | namespace Core.Common 5 | { 6 | public static class JsonHelper 7 | { 8 | public static string ToJson(this object obj) 9 | { 10 | var converters = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; 11 | 12 | return JsonConvert.SerializeObject(obj, converters); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IRepository/Core.IRepository.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.IRepository/IBaseRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.ChangeTracking; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Threading.Tasks; 7 | 8 | namespace Core.IRepository 9 | { 10 | public interface IBaseRepository where T : class, new() 11 | { 12 | ValueTask> Insert(T entity); 13 | 14 | void Update(T entity); 15 | 16 | Task Update(Expression> whereLambda, Expression> entity); 17 | 18 | Task Delete(Expression> whereLambda); 19 | 20 | Task IsExist(Expression> whereLambda); 21 | 22 | Task GetEntity(Expression> whereLambda); 23 | 24 | Task> Select(); 25 | 26 | Task> Select(Expression> whereLambda); 27 | 28 | Task, int>> Select(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc); 29 | } 30 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IRepository/IStudentRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | 3 | namespace Core.IRepository 4 | { 5 | public interface IStudentRepository : IBaseRepository 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IRepository/ITeacherRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | 3 | namespace Core.IRepository 4 | { 5 | public interface ITeacherRepository : IBaseRepository 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IRepository/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | using System.Threading.Tasks; 3 | 4 | namespace Core.IRepository 5 | { 6 | public interface IUnitOfWork 7 | { 8 | MyDbContext GetDbContext(); 9 | 10 | Task SaveChangesAsync(); 11 | } 12 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IService/Core.IService.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.IService/IBaseService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.ChangeTracking; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | using System.Threading.Tasks; 6 | 7 | namespace Core.IService 8 | { 9 | public interface IBaseService where T : class, new() 10 | { 11 | Task Insert(T entity); 12 | 13 | Task Update(T entity); 14 | 15 | Task Update(Expression> whereLambda, Expression> entity); 16 | 17 | Task Delete(Expression> whereLambda); 18 | 19 | Task IsExist(Expression> whereLambda); 20 | 21 | Task GetEntity(Expression> whereLambda); 22 | 23 | Task> Select(); 24 | 25 | Task> Select(Expression> whereLambda); 26 | 27 | Task, int>> Select(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc); 28 | } 29 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IService/IStudentService.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | using System.Threading.Tasks; 3 | 4 | namespace Core.IService 5 | { 6 | public interface IStudentService : IBaseService 7 | { 8 | Task UOW(Student student, Teacher teacher); 9 | } 10 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.IService/ITeacherService.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | 3 | namespace Core.IService 4 | { 5 | public interface ITeacherService : IBaseService 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Core.Model.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 1701;1702;1591 9 | ..\Core\Model.xml 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Core.Model.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | false 5 | 6 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Migrations/20200718085404_init.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Core.Model; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | namespace Core.Model.Migrations 9 | { 10 | [DbContext(typeof(MyDbContext))] 11 | [Migration("20200718085404_init")] 12 | partial class init 13 | { 14 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "3.1.4") 19 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 20 | 21 | modelBuilder.Entity("Core.Model.Course", b => 22 | { 23 | b.Property("Cid") 24 | .ValueGeneratedOnAdd() 25 | .HasColumnName("cid") 26 | .HasColumnType("int"); 27 | 28 | b.Property("Cname") 29 | .HasColumnName("cname") 30 | .HasColumnType("varchar(32)") 31 | .HasMaxLength(32) 32 | .IsUnicode(false); 33 | 34 | b.Property("Tid") 35 | .HasColumnName("tid") 36 | .HasColumnType("int"); 37 | 38 | b.HasKey("Cid") 39 | .HasName("PRIMARY"); 40 | 41 | b.ToTable("course"); 42 | }); 43 | 44 | modelBuilder.Entity("Core.Model.Sc", b => 45 | { 46 | b.Property("Sid") 47 | .HasColumnName("sid") 48 | .HasColumnType("int"); 49 | 50 | b.Property("Cid") 51 | .HasColumnName("cid") 52 | .HasColumnType("int"); 53 | 54 | b.Property("Score") 55 | .HasColumnName("score") 56 | .HasColumnType("int"); 57 | 58 | b.HasKey("Sid", "Cid") 59 | .HasName("PRIMARY"); 60 | 61 | b.ToTable("sc"); 62 | }); 63 | 64 | modelBuilder.Entity("Core.Model.Student", b => 65 | { 66 | b.Property("Sid") 67 | .ValueGeneratedOnAdd() 68 | .HasColumnName("sid") 69 | .HasColumnType("int"); 70 | 71 | b.Property("Sage") 72 | .HasColumnName("sage") 73 | .HasColumnType("int"); 74 | 75 | b.Property("Sname") 76 | .HasColumnName("sname") 77 | .HasColumnType("varchar(32)") 78 | .HasMaxLength(32) 79 | .IsUnicode(false); 80 | 81 | b.Property("Ssex") 82 | .HasColumnName("ssex") 83 | .HasColumnType("varchar(8)") 84 | .HasMaxLength(8) 85 | .IsUnicode(false); 86 | 87 | b.HasKey("Sid") 88 | .HasName("PRIMARY"); 89 | 90 | b.ToTable("student"); 91 | }); 92 | 93 | modelBuilder.Entity("Core.Model.Teacher", b => 94 | { 95 | b.Property("Tid") 96 | .ValueGeneratedOnAdd() 97 | .HasColumnName("tid") 98 | .HasColumnType("int"); 99 | 100 | b.Property("Tname") 101 | .HasColumnName("tname") 102 | .HasColumnType("varchar(32)") 103 | .HasMaxLength(32) 104 | .IsUnicode(false); 105 | 106 | b.HasKey("Tid") 107 | .HasName("PRIMARY"); 108 | 109 | b.ToTable("teacher"); 110 | }); 111 | #pragma warning restore 612, 618 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Migrations/20200718085404_init.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | using MySql.Data.EntityFrameworkCore.Metadata; 3 | 4 | namespace Core.Model.Migrations 5 | { 6 | public partial class init : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "course", 12 | columns: table => new 13 | { 14 | cid = table.Column(nullable: false) 15 | .Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn), 16 | cname = table.Column(unicode: false, maxLength: 32, nullable: true), 17 | tid = table.Column(nullable: false) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PRIMARY", x => x.cid); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "sc", 26 | columns: table => new 27 | { 28 | sid = table.Column(nullable: false), 29 | cid = table.Column(nullable: false), 30 | score = table.Column(nullable: false) 31 | }, 32 | constraints: table => 33 | { 34 | table.PrimaryKey("PRIMARY", x => new { x.sid, x.cid }); 35 | }); 36 | 37 | migrationBuilder.CreateTable( 38 | name: "student", 39 | columns: table => new 40 | { 41 | sid = table.Column(nullable: false) 42 | .Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn), 43 | sname = table.Column(unicode: false, maxLength: 32, nullable: true), 44 | sage = table.Column(nullable: false), 45 | ssex = table.Column(unicode: false, maxLength: 8, nullable: true) 46 | }, 47 | constraints: table => 48 | { 49 | table.PrimaryKey("PRIMARY", x => x.sid); 50 | }); 51 | 52 | migrationBuilder.CreateTable( 53 | name: "teacher", 54 | columns: table => new 55 | { 56 | tid = table.Column(nullable: false) 57 | .Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn), 58 | tname = table.Column(unicode: false, maxLength: 32, nullable: true) 59 | }, 60 | constraints: table => 61 | { 62 | table.PrimaryKey("PRIMARY", x => x.tid); 63 | }); 64 | } 65 | 66 | protected override void Down(MigrationBuilder migrationBuilder) 67 | { 68 | migrationBuilder.DropTable( 69 | name: "course"); 70 | 71 | migrationBuilder.DropTable( 72 | name: "sc"); 73 | 74 | migrationBuilder.DropTable( 75 | name: "student"); 76 | 77 | migrationBuilder.DropTable( 78 | name: "teacher"); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Migrations/MyDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Core.Model; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | 7 | namespace Core.Model.Migrations 8 | { 9 | [DbContext(typeof(MyDbContext))] 10 | partial class MyDbContextModelSnapshot : ModelSnapshot 11 | { 12 | protected override void BuildModel(ModelBuilder modelBuilder) 13 | { 14 | #pragma warning disable 612, 618 15 | modelBuilder 16 | .HasAnnotation("ProductVersion", "3.1.4") 17 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 18 | 19 | modelBuilder.Entity("Core.Model.Course", b => 20 | { 21 | b.Property("Cid") 22 | .ValueGeneratedOnAdd() 23 | .HasColumnName("cid") 24 | .HasColumnType("int"); 25 | 26 | b.Property("Cname") 27 | .HasColumnName("cname") 28 | .HasColumnType("varchar(32)") 29 | .HasMaxLength(32) 30 | .IsUnicode(false); 31 | 32 | b.Property("Tid") 33 | .HasColumnName("tid") 34 | .HasColumnType("int"); 35 | 36 | b.HasKey("Cid") 37 | .HasName("PRIMARY"); 38 | 39 | b.ToTable("course"); 40 | }); 41 | 42 | modelBuilder.Entity("Core.Model.Sc", b => 43 | { 44 | b.Property("Sid") 45 | .HasColumnName("sid") 46 | .HasColumnType("int"); 47 | 48 | b.Property("Cid") 49 | .HasColumnName("cid") 50 | .HasColumnType("int"); 51 | 52 | b.Property("Score") 53 | .HasColumnName("score") 54 | .HasColumnType("int"); 55 | 56 | b.HasKey("Sid", "Cid") 57 | .HasName("PRIMARY"); 58 | 59 | b.ToTable("sc"); 60 | }); 61 | 62 | modelBuilder.Entity("Core.Model.Student", b => 63 | { 64 | b.Property("Sid") 65 | .ValueGeneratedOnAdd() 66 | .HasColumnName("sid") 67 | .HasColumnType("int"); 68 | 69 | b.Property("Sage") 70 | .HasColumnName("sage") 71 | .HasColumnType("int"); 72 | 73 | b.Property("Sname") 74 | .HasColumnName("sname") 75 | .HasColumnType("varchar(32)") 76 | .HasMaxLength(32) 77 | .IsUnicode(false); 78 | 79 | b.Property("Ssex") 80 | .HasColumnName("ssex") 81 | .HasColumnType("varchar(8)") 82 | .HasMaxLength(8) 83 | .IsUnicode(false); 84 | 85 | b.HasKey("Sid") 86 | .HasName("PRIMARY"); 87 | 88 | b.ToTable("student"); 89 | }); 90 | 91 | modelBuilder.Entity("Core.Model.Teacher", b => 92 | { 93 | b.Property("Tid") 94 | .ValueGeneratedOnAdd() 95 | .HasColumnName("tid") 96 | .HasColumnType("int"); 97 | 98 | b.Property("Tname") 99 | .HasColumnName("tname") 100 | .HasColumnType("varchar(32)") 101 | .HasMaxLength(32) 102 | .IsUnicode(false); 103 | 104 | b.HasKey("Tid") 105 | .HasName("PRIMARY"); 106 | 107 | b.ToTable("teacher"); 108 | }); 109 | #pragma warning restore 612, 618 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/MySqlContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace Core.Model 4 | { 5 | public partial class MyDbContext : DbContext 6 | { 7 | public MyDbContext() 8 | { 9 | } 10 | 11 | public MyDbContext(DbContextOptions options) 12 | : base(options) 13 | { 14 | } 15 | 16 | public virtual DbSet Course { get; set; } 17 | public virtual DbSet Sc { get; set; } 18 | public virtual DbSet Student { get; set; } 19 | public virtual DbSet Teacher { get; set; } 20 | 21 | protected override void OnModelCreating(ModelBuilder modelBuilder) 22 | { 23 | modelBuilder.Entity(entity => 24 | { 25 | entity.HasKey(e => e.Cid) 26 | .HasName("PRIMARY"); 27 | 28 | entity.ToTable("course"); 29 | 30 | entity.Property(e => e.Cid).HasColumnName("cid"); 31 | 32 | entity.Property(e => e.Cname) 33 | .HasColumnName("cname") 34 | .HasMaxLength(32) 35 | .IsUnicode(false); 36 | 37 | entity.Property(e => e.Tid).HasColumnName("tid"); 38 | }); 39 | 40 | modelBuilder.Entity(entity => 41 | { 42 | entity.HasKey(e => new { e.Sid, e.Cid }) 43 | .HasName("PRIMARY"); 44 | 45 | entity.ToTable("sc"); 46 | 47 | entity.Property(e => e.Sid).HasColumnName("sid"); 48 | 49 | entity.Property(e => e.Cid).HasColumnName("cid"); 50 | 51 | entity.Property(e => e.Score).HasColumnName("score"); 52 | }); 53 | 54 | modelBuilder.Entity(entity => 55 | { 56 | entity.HasKey(e => e.Sid) 57 | .HasName("PRIMARY"); 58 | 59 | entity.ToTable("student"); 60 | 61 | entity.Property(e => e.Sid).HasColumnName("sid"); 62 | 63 | entity.Property(e => e.Sage).HasColumnName("sage"); 64 | 65 | entity.Property(e => e.Sname) 66 | .HasColumnName("sname") 67 | .HasMaxLength(32) 68 | .IsUnicode(false); 69 | 70 | entity.Property(e => e.Ssex) 71 | .HasColumnName("ssex") 72 | .HasMaxLength(8) 73 | .IsUnicode(false); 74 | }); 75 | 76 | modelBuilder.Entity(entity => 77 | { 78 | entity.HasKey(e => e.Tid) 79 | .HasName("PRIMARY"); 80 | 81 | entity.ToTable("teacher"); 82 | 83 | entity.Property(e => e.Tid).HasColumnName("tid"); 84 | 85 | entity.Property(e => e.Tname) 86 | .HasColumnName("tname") 87 | .HasMaxLength(32) 88 | .IsUnicode(false); 89 | }); 90 | 91 | OnModelCreatingPartial(modelBuilder); 92 | } 93 | 94 | partial void OnModelCreatingPartial(ModelBuilder modelBuilder); 95 | } 96 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/Response.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Core.Model 4 | { 5 | public class Response 6 | { 7 | public int Code { get; set; } 8 | 9 | public string Message { get; set; } 10 | 11 | public Response() 12 | { 13 | Code = 200; 14 | Message = "操作成功"; 15 | } 16 | } 17 | 18 | public class Response 19 | { 20 | public int Code { get; set; } 21 | 22 | public string Message { get; set; } 23 | 24 | public List Data { get; set; } 25 | 26 | public Response() 27 | { 28 | Code = 200; 29 | Message = "操作成功"; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/School/Course.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Model 2 | { 3 | public partial class Course 4 | { 5 | public int Cid { get; set; } 6 | 7 | public string Cname { get; set; } 8 | 9 | public int Tid { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/School/Sc.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Model 2 | { 3 | public partial class Sc 4 | { 5 | public int Sid { get; set; } 6 | 7 | public int Cid { get; set; } 8 | 9 | public int Score { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/School/Student.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Model 2 | { 3 | public partial class Student 4 | { 5 | public int Sid { get; set; } 6 | 7 | public string Sname { get; set; } 8 | 9 | public int Sage { get; set; } 10 | 11 | public string Ssex { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Model/School/Teacher.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Model 2 | { 3 | public partial class Teacher 4 | { 5 | public int Tid { get; set; } 6 | 7 | public string Tname { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Repository/BaseRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.Model; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.ChangeTracking; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Threading.Tasks; 9 | using Z.EntityFramework.Plus; 10 | 11 | namespace Core.Repository 12 | { 13 | public class BaseRepository where T : class, new() 14 | { 15 | private readonly MyDbContext myDbContext; 16 | 17 | public BaseRepository(MyDbContext myDbContext) 18 | { 19 | this.myDbContext = myDbContext; 20 | } 21 | 22 | public async ValueTask> Insert(T entity) 23 | { 24 | return await myDbContext.Set().AddAsync(entity); 25 | } 26 | 27 | public void Update(T entity) 28 | { 29 | myDbContext.Set().Update(entity); 30 | } 31 | 32 | public async Task Update(Expression> whereLambda, Expression> entity) 33 | { 34 | return await myDbContext.Set().Where(whereLambda).UpdateAsync(entity); 35 | } 36 | 37 | public async Task Delete(Expression> whereLambda) 38 | { 39 | return await myDbContext.Set().Where(whereLambda).DeleteAsync(); 40 | } 41 | 42 | public async Task IsExist(Expression> whereLambda) 43 | { 44 | return await myDbContext.Set().AnyAsync(whereLambda); 45 | } 46 | 47 | public async Task GetEntity(Expression> whereLambda) 48 | { 49 | return await myDbContext.Set().AsNoTracking().FirstOrDefaultAsync(whereLambda); 50 | } 51 | 52 | public async Task> Select() 53 | { 54 | return await myDbContext.Set().ToListAsync(); 55 | } 56 | 57 | public async Task> Select(Expression> whereLambda) 58 | { 59 | return await myDbContext.Set().Where(whereLambda).ToListAsync(); 60 | } 61 | 62 | public async Task, int>> Select(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc) 63 | { 64 | var total = await myDbContext.Set().Where(whereLambda).CountAsync(); 65 | 66 | if (isAsc) 67 | { 68 | var entities = await myDbContext.Set().Where(whereLambda) 69 | .OrderBy(orderByLambda) 70 | .Skip(pageSize * (pageIndex - 1)) 71 | .Take(pageSize).ToListAsync(); 72 | 73 | return new Tuple, int>(entities, total); 74 | } 75 | else 76 | { 77 | var entities = await myDbContext.Set().Where(whereLambda) 78 | .OrderByDescending(orderByLambda) 79 | .Skip(pageSize * (pageIndex - 1)) 80 | .Take(pageSize).ToListAsync(); 81 | 82 | return new Tuple, int>(entities, total); 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Repository/Core.Repository.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Repository/StudentRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Core.Model; 3 | 4 | namespace Core.Repository 5 | { 6 | public class StudentRepository : BaseRepository, IStudentRepository 7 | { 8 | public StudentRepository(MyDbContext myDbContext) : base(myDbContext) 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Repository/TeacherRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Core.Model; 3 | 4 | namespace Core.Repository 5 | { 6 | public class TeacherRepository : BaseRepository, ITeacherRepository 7 | { 8 | public TeacherRepository(MyDbContext myDbContext) : base(myDbContext) 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Repository/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Core.Model; 3 | using System; 4 | using System.Threading.Tasks; 5 | 6 | namespace Core.Repository 7 | { 8 | public class UnitOfWork : IUnitOfWork 9 | { 10 | private readonly MyDbContext myDbContext; 11 | 12 | public UnitOfWork(MyDbContext myDbContext) 13 | { 14 | this.myDbContext = myDbContext; 15 | } 16 | 17 | public MyDbContext GetDbContext() 18 | { 19 | return myDbContext; 20 | } 21 | 22 | public async Task SaveChangesAsync() 23 | { 24 | return await myDbContext.SaveChangesAsync(); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Service/BaseService.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Microsoft.EntityFrameworkCore.ChangeTracking; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Threading.Tasks; 8 | 9 | namespace Core.Service 10 | { 11 | public class BaseService where T : class, new() 12 | { 13 | protected IUnitOfWork unitOfWork; 14 | protected IBaseRepository currentRepository; 15 | 16 | public BaseService(IUnitOfWork unitOfWork, IBaseRepository currentRepository) 17 | { 18 | this.unitOfWork = unitOfWork; 19 | this.currentRepository = currentRepository; 20 | } 21 | 22 | public async Task Insert(T entity) 23 | { 24 | await currentRepository.Insert(entity); 25 | return await unitOfWork.SaveChangesAsync(); 26 | } 27 | 28 | public async Task Update(T entity) 29 | { 30 | currentRepository.Update(entity); 31 | return await unitOfWork.SaveChangesAsync(); 32 | } 33 | 34 | public async Task Update(Expression> whereLambda, Expression> entity) 35 | { 36 | await currentRepository.Update(whereLambda, entity); 37 | return await unitOfWork.SaveChangesAsync(); 38 | } 39 | 40 | public async Task Delete(Expression> whereLambda) 41 | { 42 | await currentRepository.Delete(whereLambda); 43 | return await unitOfWork.SaveChangesAsync(); 44 | } 45 | 46 | public async Task IsExist(Expression> whereLambda) 47 | { 48 | return await currentRepository.IsExist(whereLambda); 49 | } 50 | 51 | public async Task GetEntity(Expression> whereLambda) 52 | { 53 | return await currentRepository.GetEntity(whereLambda); 54 | } 55 | 56 | public async Task> Select() 57 | { 58 | return await currentRepository.Select(); 59 | } 60 | 61 | public async Task> Select(Expression> whereLambda) 62 | { 63 | return await currentRepository.Select(whereLambda); 64 | } 65 | 66 | public async Task, int>> Select(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc) 67 | { 68 | return await currentRepository.Select(pageSize, pageIndex, whereLambda, orderByLambda, isAsc); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Service/Core.Service.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /RepositoryDemo/Core.Service/StudentService.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Core.IService; 3 | using Core.Model; 4 | using System.Threading.Tasks; 5 | 6 | namespace Core.Service 7 | { 8 | public class StudentService : BaseService, IStudentService 9 | { 10 | private readonly ITeacherRepository teacherRepository; 11 | 12 | public StudentService(IUnitOfWork unitOfWork, IBaseRepository currentRepository, ITeacherRepository teacherRepository) : base(unitOfWork, currentRepository) 13 | 14 | { 15 | this.teacherRepository = teacherRepository; 16 | } 17 | 18 | public async Task UOW(Student student, Teacher teacher) 19 | { 20 | await currentRepository.Insert(student); 21 | await teacherRepository.Insert(teacher); 22 | 23 | await unitOfWork.SaveChangesAsync(); 24 | 25 | return true; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.Service/TeacherService.cs: -------------------------------------------------------------------------------- 1 | using Core.IRepository; 2 | using Core.IService; 3 | using Core.Model; 4 | 5 | namespace Core.Service 6 | { 7 | public class TeacherService : BaseService, ITeacherService 8 | { 9 | public TeacherService(IUnitOfWork unitOfWork, IBaseRepository currentRepository) : base(unitOfWork, currentRepository) 10 | { 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30104.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "Core\Core.csproj", "{44CCF475-6919-430A-86A6-F645EA9BFC33}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Common", "Core.Common\Core.Common.csproj", "{54121B6A-080F-4A25-B224-A84B59368121}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.IRepository", "Core.IRepository\Core.IRepository.csproj", "{AE895313-6F38-408E-B77A-6A194056FFF5}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.IService", "Core.IService\Core.IService.csproj", "{E2D45E2B-29A8-4C3C-8B8D-617357D5503F}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Model", "Core.Model\Core.Model.csproj", "{DF51BCE5-3581-4072-A095-86FBA8296F2D}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Repository", "Core.Repository\Core.Repository.csproj", "{F36F8AB0-2DB4-4743-895E-508E119FC9B5}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Service", "Core.Service\Core.Service.csproj", "{AD18AC5E-DF9D-4EAF-88D4-E72BCBFA769C}" 19 | EndProject 20 | Global 21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 22 | Debug|Any CPU = Debug|Any CPU 23 | Release|Any CPU = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {44CCF475-6919-430A-86A6-F645EA9BFC33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {44CCF475-6919-430A-86A6-F645EA9BFC33}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {44CCF475-6919-430A-86A6-F645EA9BFC33}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {44CCF475-6919-430A-86A6-F645EA9BFC33}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {54121B6A-080F-4A25-B224-A84B59368121}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {54121B6A-080F-4A25-B224-A84B59368121}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {54121B6A-080F-4A25-B224-A84B59368121}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {54121B6A-080F-4A25-B224-A84B59368121}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {AE895313-6F38-408E-B77A-6A194056FFF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {AE895313-6F38-408E-B77A-6A194056FFF5}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {AE895313-6F38-408E-B77A-6A194056FFF5}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {AE895313-6F38-408E-B77A-6A194056FFF5}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {E2D45E2B-29A8-4C3C-8B8D-617357D5503F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {E2D45E2B-29A8-4C3C-8B8D-617357D5503F}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {E2D45E2B-29A8-4C3C-8B8D-617357D5503F}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {E2D45E2B-29A8-4C3C-8B8D-617357D5503F}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {DF51BCE5-3581-4072-A095-86FBA8296F2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {DF51BCE5-3581-4072-A095-86FBA8296F2D}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {DF51BCE5-3581-4072-A095-86FBA8296F2D}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {DF51BCE5-3581-4072-A095-86FBA8296F2D}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {F36F8AB0-2DB4-4743-895E-508E119FC9B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {F36F8AB0-2DB4-4743-895E-508E119FC9B5}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {F36F8AB0-2DB4-4743-895E-508E119FC9B5}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {F36F8AB0-2DB4-4743-895E-508E119FC9B5}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {AD18AC5E-DF9D-4EAF-88D4-E72BCBFA769C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {AD18AC5E-DF9D-4EAF-88D4-E72BCBFA769C}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {AD18AC5E-DF9D-4EAF-88D4-E72BCBFA769C}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {AD18AC5E-DF9D-4EAF-88D4-E72BCBFA769C}.Release|Any CPU.Build.0 = Release|Any CPU 54 | EndGlobalSection 55 | GlobalSection(SolutionProperties) = preSolution 56 | HideSolutionNode = FALSE 57 | EndGlobalSection 58 | GlobalSection(ExtensibilityGlobals) = postSolution 59 | SolutionGuid = {1016EA57-8143-4CD1-B025-5D1A8A0DCD5F} 60 | EndGlobalSection 61 | EndGlobal 62 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/Controllers/StudentController.cs: -------------------------------------------------------------------------------- 1 | using Core.Common; 2 | using Core.IService; 3 | using Core.Model; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Threading.Tasks; 7 | 8 | namespace Core.Controllers 9 | { 10 | [Route("api/[controller]/[action]")] 11 | [ApiController] 12 | public class StudentController : ControllerBase 13 | { 14 | private readonly IStudentService studentService; 15 | 16 | public StudentController(IStudentService studentService) 17 | { 18 | this.studentService = studentService; 19 | } 20 | 21 | [HttpPost] 22 | public async Task Insert([FromForm] Student student) 23 | { 24 | try 25 | { 26 | await studentService.Insert(student); 27 | 28 | return new Response().ToJson(); 29 | } 30 | catch (Exception e) 31 | { 32 | return new Response() { Code = 500, Message = e.Message }.ToJson(); 33 | } 34 | } 35 | 36 | [HttpPost] 37 | public async Task Update([FromForm] Student student) 38 | { 39 | try 40 | { 41 | //await studentService.Update(student); 42 | await studentService.Update(t => t.Sid == student.Sid, t => new Student() { Sage = student.Sage }); 43 | 44 | return new Response().ToJson(); 45 | } 46 | catch (Exception e) 47 | { 48 | return new Response() { Code = 500, Message = e.Message }.ToJson(); 49 | } 50 | } 51 | 52 | [HttpPost] 53 | public async Task Delete(int id) 54 | { 55 | try 56 | { 57 | await studentService.Delete(t => t.Sid == id); 58 | 59 | return new Response().ToJson(); 60 | } 61 | catch (Exception e) 62 | { 63 | return new Response() { Code = 500, Message = e.Message }.ToJson(); 64 | } 65 | } 66 | 67 | [HttpGet] 68 | public async Task Select() 69 | { 70 | try 71 | { 72 | var students = await studentService.Select(t => true); 73 | return new Response() { Data = students }.ToJson(); 74 | } 75 | catch (Exception e) 76 | { 77 | return new Response() { Code = 500, Message = e.Message }.ToJson(); 78 | } 79 | } 80 | 81 | [HttpPost] 82 | public async Task UOW([FromForm] Student student) 83 | { 84 | try 85 | { 86 | Teacher teacher = new Teacher() { Tid = student.Sid, Tname = student.Sname }; 87 | 88 | await studentService.UOW(student, teacher); 89 | 90 | return new Response().ToJson(); 91 | } 92 | catch (Exception e) 93 | { 94 | return new Response() { Code = 500, Message = e.Message }.ToJson(); 95 | } 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core/Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | ..\Core\Core.xml 9 | 1701;1702;1591 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | Always 40 | 41 | 42 | Always 43 | 44 | 45 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/Core.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | true 5 | ApiControllerEmptyScaffolder 6 | root/Controller 7 | 600 8 | True 9 | False 10 | True 11 | 12 | False 13 | 14 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/Core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Core 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/Model.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Core.Model 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac.Extensions.DependencyInjection; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Hosting; 4 | 5 | namespace Core 6 | { 7 | public class Program 8 | { 9 | public static void Main(string[] args) 10 | { 11 | CreateHostBuilder(args).Build().Run(); 12 | } 13 | 14 | public static IHostBuilder CreateHostBuilder(string[] args) => 15 | Host.CreateDefaultBuilder(args) 16 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 17 | .ConfigureWebHostDefaults(webBuilder => 18 | { 19 | webBuilder.UseStartup(); 20 | }); 21 | } 22 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:51917", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Core": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "weatherforecast", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core/Startup.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Core.Model; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Hosting; 9 | using Microsoft.OpenApi.Models; 10 | using System; 11 | using System.IO; 12 | using System.Reflection; 13 | 14 | namespace Core 15 | { 16 | public class Startup 17 | { 18 | public Startup(IConfiguration configuration) 19 | { 20 | Configuration = configuration; 21 | } 22 | 23 | public IConfiguration Configuration { get; } 24 | 25 | public void ConfigureServices(IServiceCollection services) 26 | { 27 | services.AddControllers(); 28 | 29 | var basePath = AppContext.BaseDirectory; 30 | services.AddSwaggerGen(c => 31 | { 32 | c.SwaggerDoc("v1", new OpenApiInfo 33 | { 34 | Version = "V1", 35 | Title = "Core", 36 | }); 37 | 38 | c.IncludeXmlComments(Path.Combine(basePath, "Core.xml"), true); 39 | c.IncludeXmlComments(Path.Combine(basePath, "Model.xml"), true); 40 | }); 41 | 42 | services.AddDbContext(options => options.UseMySQL(Configuration["ConnectionStrings:MySql"])); 43 | } 44 | 45 | public void ConfigureContainer(ContainerBuilder builder) 46 | { 47 | var basePath = AppContext.BaseDirectory; 48 | var service = Path.Combine(basePath, "Core.Service.dll"); 49 | var repository = Path.Combine(basePath, "Core.Repository.dll"); 50 | 51 | builder.RegisterAssemblyTypes(Assembly.LoadFrom(service)) 52 | .AsImplementedInterfaces() 53 | .InstancePerDependency(); 54 | 55 | builder.RegisterAssemblyTypes(Assembly.LoadFrom(repository)) 56 | .AsImplementedInterfaces() 57 | .InstancePerDependency(); 58 | } 59 | 60 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 61 | { 62 | app.UseCors(options => 63 | { 64 | options.AllowAnyMethod() 65 | .SetIsOriginAllowed(_ => true) 66 | .AllowAnyHeader() 67 | .AllowCredentials(); 68 | }); 69 | 70 | if (env.IsDevelopment()) 71 | { 72 | app.UseDeveloperExceptionPage(); 73 | } 74 | 75 | app.UseSwagger(); 76 | app.UseSwaggerUI(c => 77 | { 78 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API V1"); 79 | c.RoutePrefix = ""; 80 | }); 81 | 82 | app.UseStaticFiles(); 83 | 84 | app.UseRouting(); 85 | 86 | app.UseAuthorization(); 87 | 88 | app.UseEndpoints(endpoints => 89 | { 90 | endpoints.MapControllers(); 91 | }); 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /RepositoryDemo/Core/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RepositoryDemo/Core/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "ConnectionStrings": { 10 | "MySql": "Server=192.168.1.4;Database=School;Uid=root;Pwd=admin;" 11 | }, 12 | "AllowedHosts": "*" 13 | } --------------------------------------------------------------------------------