# orz.mouxianyu **Repository Path**: modochear/orz.mouxianyu ## Basic Information - **Project Name**: orz.mouxianyu - **Description**: 基于netcore2.2的web后端框架——咸鱼框架 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2020-09-23 - **Last Updated**: 2024-09-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 咸鱼框架V1 ###对于完全新手的小白,请看目录下的教程文档 *示例代码说明(使用教程).docx ### 开发环境 * .net core sdk 2.2 SDK * [Download .NET Core 2.2 SDK ](https://dotnet.microsoft.com/download/dotnet-core/2.2) * Visual Studio 2019(这里编写框架用的2019,其他版本没试过,但是应该也可以) #### 解决方案中命名空间说明 | *orz.mouxianyu | 咸鱼框架解决方案 | |----------------------------|--------------------| | * orz.mouxianyu.Controllers | controller层 | | * orz.mouxianyu.service | 业务层 接口 | | * orz.mouxianyu.service.lmpl | 业务层 服务 | | * orz.mouxianyu.Extensions | 扩展(一些注入startup的内容) | | * orz.mouxianyu.Extension.ToolClass | 封装的一些工具类(如加密工具、返回json格式化工具) | | * orz.mouxianyu.Extension.Exceptions | 封装报错信息 | | * orz.mouxianyu.Extension.View | View层 | | * appsetting.json | 配置文件 | | * launchSetting.json | 系统配置 | #### 配置说明 ##### 开启 Swagger api 文档 通过在 Startup.cs 中配置并启用 Swagger ```csharp /* *这里配置 Swagger api 文档系统。 *startup中:services.AddSwaggerDocumentation(); *orz.mouxianyu.Extensions中:SwaggerServiceExtensions */ services.AddSwaggerGen(options => { ...... } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ... app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1"); ...... }); ...... } ``` #### 配置 注入 SqlConnection * 数据库访问 SqlConnection 和 Dapper 组合 * dapper 使用 参考 * [https://github.com/StackExchange/Dapper](https://github.com/StackExchange/Dapper) * [https://stackexchange.github.io/Dapper/](https://stackexchange.github.io/Dapper/) * 通过在 Startup.cs 中注入 SqlConnection,AddSqlClient中配置 ```csharp public void ConfigureServices(IServiceCollection services) { ....注入 SqlConnection services.AddScoped((ctc) => { string connectionString = Configuration["MSSQLConnection:SqlConnectionString"]; SqlConnection con = new SqlConnection(connectionString); return con; }); } ``` > appsettings.json ```csharp ...... "MSSQLConnection": { "SqlConnectionString": "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=IdentityServer4;Integrated Security=True" } ``` #### 配置 注入JWT身份验证 *在startup中注入:services.AddJwtAuthentication(Configuration); *AddJwtAuthentication中配置 ```csharp services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "orz.mouxianyu", ValidAudience = "orz.mouxianyu", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecurityKey"])) }; }); ``` **在 Controller 或 Action 上使用 标签 以启用授权访问** * [Authorize("dataEventRecordsAdmin")] * [Authorize] * 在 Startup.cs 中启用全局 Authorize 认证 ```csharp public void ConfigureServices(IServiceCollection services) { ...... //注册 全局 Authorization 验证器 var guestPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvcCore(opt => { opt.Filters.Add(new AuthorizeFilter(authzPolicy)); }) .AddApiExplorer() .AddAuthorization() .AddJsonFormatters(opts => { opts.Formatting = Formatting.Indented; opts.TypeNameHandling = TypeNameHandling.None;//不包含 对象类型名称 opts.NullValueHandling = NullValueHandling.Include;//序列化是包含null 值 opts.ContractResolver = new CamelCasePropertyNamesContractResolver();//json 首字母小写 格式处理 //opts.ContractResolver = new DefaultContractResolver();//json默认处理 json处理方式只能启用一个 //日期类型默认格式化处理 opts.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; opts.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } ``` #### 以下为2019年5月13日更新内容: #### 配置报错信息 * 封装报错信息使用的是serilog,详情参见[https://github.com/serilog/serilog](https://github.com/serilog/serilog) * 在starup中注入:app.UseMiddleware(); * 在orz.mouxianyu.Extension.Exceptions中封装报错信息 * 在program.cs中配置报错文件: ```csharp Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .Enrich.FromLogContext() .WriteTo.RollingFile(AppDomain.CurrentDomain.BaseDirectory + @"\logs\orz.mouxianyu.log",//报错文件 fileSizeLimitBytes: 1_000_000,//文件大小 shared: true, flushToDiskInterval: TimeSpan.FromSeconds(5))//报错等级(详情参见serilog官网或github) .CreateLogger(); ``` #### websocket * 参考文档[https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/websockets?view=aspnetcore-2.2](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/websockets?view=aspnetcore-2.2) * 在starup中注入: ``` csharp var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); ``` * 接受 WebSocket 请求: ```csharp app.Use(async (context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); ``` * 发送和接收消息: ```csahrp private async Task Echo(HttpContext context, WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } ``` * 示例代码/wwwroot/index.html,地址https://localhost:你的端口/index.html ### 第一版暂时只有这些功能,以后还会更新(大概,发出咕咕咕的声音) * 下一版预定加入:1.本地日志(2019年5月13日已完成)与数据库日志(咕咕咕),2.hangfire,3.mq,4.websocket(2019年5月13日已完成),5.还没想好,写多少是多少吧 ### 使用过程中发现bug欢迎反馈至邮箱 stardustrunes@gmail.com ### 欢迎关注本人b站空间,不定时发布相关教程(大概,发出咕咕咕的声音) * B站@某咸鱼orz [https://space.bilibili.com/8424446] * 本框架仅限个人学习交流,个人及小规模团队非商业项目请随意,只要在应用中声明作者信息(附上GitHub地址)即可,商业用途请联系作者 * 2019年4月16日19:41:00