.NET Core 包括.NET Core Runtime 和 .NET Core SDK:
- .NET Core = 应用运行依赖的 .NET Core Runtime
- .NET Core SDK = 使用.NET Core开发应用.NET Core Runtime 和 SDK+CLI(Software Development Kit/Command Line Interface) 工具
一、说明:
本文是教大家如何快速搭建一个.net core 项目。为了快速和简单,本项目采用UtilsSharp框架搭建,只需要简单配置就可以马上搭建完成。项目采用简单三层思想,框架采用.net core 3.1,数据库采用mysql+ElasticSearch,大家可以根据自己的项目需求选择删减,包含依赖注入(autofac)、日志输出、数据库处理、出入参规范、swagger、公共工具类等。废话不多说,开始吧!
框架常用Nuget包:
UtilsSharp
UtilsSharp.AspNetCore
UtilsSharp.Redis
UtilsSharp.ElasticSearch
UtilsSharp.MySql
UtilsSharp.MsSql
UtilsSharp.RabbitMq
UtilsSharp.LoggerHelper
二、开始搭建:
1.打开vs2019,创建.net core新项目:
2.为了方便好记,我的项目名称就叫Dnc,意思是Dot Net Core 的首写字母,大家可以根据自己的业务取名称,然后选择好项目要放置的路径。
3.选择好项目框架,创建空的Asp.NET Core 应用程序的空项目模板,大家也可以选择API和Web应用程序(根据项目需求,是前后端分离开接口还是做页面),选择“空”主要是为了不去下载一些没必要的东西。
4.创建数据模型层、数据层、业务逻辑层。右键选择解决方案。
5.创建类库名称分别叫:Dnc.Data、Dnc.DataSource、Dnc.Service,框架选用.net standard2.0版本
6.Dnc下面Nuget,搜索 UtilsSharp.AspNetCore,安装
7.配置Program.cs
8.配置Startup.cs
①默认的程序
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Dnc { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); } } }
②配置后
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AspNetCore; using AspNetCore.Autofac; using AspNetCore.Swagger; using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Dnc { public class Startup:AutofacStartup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //添加控制器服务 services.AddControllers(); //添加扩展服务,如果参数不填则用默认的swagger配置 services.AddAspNetCoreExtensions(new SwaggerDocOptions { Name = "v1", OpenApiInfo = { Title = "Dnc项目", Version = "v1", Description = "Dnc项目接口" } }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); //注册扩展 app.UseAspNetCoreExtensions(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } /// <summary> /// 依赖注入映射 /// </summary> /// <param name="builder">builder</param> public override void ConfigureContainer(ContainerBuilder builder) { //无监控收集错误日志 Init(builder); //aop Exception错误日志监控 //Init<LoggerInterceptor>(builder); } } }
Init(builder) 是无监控日志,Init<LoggerInterceptor>(builder)是aop Exception错误日志监控。会try catch收集Service里面的日志。至于AOP是什么大家可以自行百度。LoggerInterceptor类,大家可以实现Interceptor接口自定义自己要过滤的东西。
9.大项目都是分功能块的,所以我们创建个Area,对项目各个功能进行分块
10.Dnc.Service Nuget 搜索UtilsSharp工具类安装
11.Dnc.Service 新建Admin功能服务,Implementation文件夹里面是实现
12.IUserInfoService接口实现IUnitOfWorkDependency接口,绑定依赖注入关系
using System; using System.Collections.Generic; using System.Text; using UtilsSharp.Dependency; using UtilsSharp.Standard; namespace Dnc.Service.Admin { /// <summary> /// 用户信息服务 /// </summary> public interface IUserInfoService : IUnitOfWorkDependency { /// <summary> /// 获取用户信息 /// </summary> /// <returns></returns> BaseResult<UserInfo> Get(); } /// <summary> /// 用户信息 /// </summary> public class UserInfo { /// <summary> /// 用户名 /// </summary> public string UserName { set; get; } /// <summary> /// 手机号 /// </summary> public string Mobile { set; get; } /// <summary> /// 年龄 /// </summary> public int Age { set; get; } /// <summary> /// 支付条数 /// </summary> public int PayCount { set; get; } } }
13.UserInfoService实现IUserInfoService接口
using System; using System.Collections.Generic; using System.Text; using UtilsSharp.Standard; namespace Dnc.Service.Admin.Implementation { /// <summary> /// 用户信息服务 /// </summary> public class UserInfoService: IUserInfoService { private readonly IPayRecordService _payRecordService; public UserInfoService(IPayRecordService payRecordService) { _payRecordService = payRecordService; } /// <summary> /// 获取用户信息 /// </summary> /// <returns></returns> public BaseResult<UserInfo> Get() { var result=new BaseResult<UserInfo>(); //查询数据库..... //if (false) //{ // result.SetError("未查询到该条记录"); // return result; //} var r = _payRecordService.GetRecord(); if (r.Code != 200) { result.SetError(r.Msg,r.Code); return result; } result.Result = new UserInfo {UserName = "Agoling", Mobile = "136xxxxxxxx", Age = 10, PayCount = r.Result}; return result; } } }
14.IPayRecordService接口实现IUnitOfWorkDependency接口,绑定依赖注入关系
using System; using System.Collections.Generic; using System.Text; using UtilsSharp.Dependency; using UtilsSharp.Standard; namespace Dnc.Service.Admin { /// <summary> /// 支付记录服务 /// </summary> public interface IPayRecordService : IUnitOfWorkDependency { /// <summary> /// 获取记录条数 /// </summary> /// <returns></returns> BaseResult<int> GetRecord(); } }
15.PayRecordService实现IPayRecordService接口
using System; using System.Collections.Generic; using System.Text; using UtilsSharp.Standard; namespace Dnc.Service.Admin.Implementation { /// <summary> /// 支付记录服务 /// </summary> public class PayRecordService: IPayRecordService { /// <summary> /// 获取记录条数 /// </summary> /// <returns></returns> public BaseResult<int> GetRecord() { var result=new BaseResult<int>(); //查数据库 //if (false) //{ // result.SetError("无法连接数据库",8000); // return result; //} result.Result = 101; return result; } } }
16.Dnc项目添加Dnc.Service项目,控制器调用业务层获取数据,配置好路由。
17.启动项目,后缀加swagger即可看到项目
18.由于没有注释,所以大家可以按下面的方法,即可显示出注释。Dnc右键属性->XML文档文件打勾
19.测试数据
20.以上是先简单模拟数据走通依赖注入和swagger功能,数据库这块的后面再单独讲
本项目源代码:https://github.com/agoling/dnc
什么是
Asp.Net core
我相信很多
C# Developer
已经对于.net core
不算陌生了,就算没有正式使用相信也应该有所了解。微软在推出来.net core
的同时为了方便一些原有的项目可以方便迁移,同时推出了Asp.net core
。那么.net core
和Asp.net core
是不是同一个东西呢?如果不是又有什么区别呢?下面我们分别说明一下,首先
Asp.net core
和.net core
肯定不是同一个东西(废话,如果是同一个东西还写这么多干啥!)。
Asp.net core
其实就是仍然基于.net Full Framework
(最低要求Framework 4.6.2
)的项目, 但同时保留了.net core
一些新的设置理念,比如Asp.net core
默认使用Kestrel
作为Http
请求的监听器,而不是使用原来庞大的Https.sys
。Kestrel
不仅仅是微软下一代的跨平台Http
请求监听器,同时还提供了比Https.sys
更轻量级以及更快速的Http
请求处理。另除此之外,Asp.net core
与原来的Web
设计另一个最大的区别在于Asp.net core
(及.net core
)完全抛弃了原来的使用管道模式来接收以及处理HttpRequest
。在Asp.net core
中允许处理中间件(Middleware
)来对所有的HttpRequest
来进行请求,当请求被接收到时,Asp.net core
会调用注册的中间件(按照注册的顺序)对HttpRequest
进行处理。这样做相比与原来使用HttpApplication
的管道方式而言,其优势在于完全由开发人员决定HttpRequest
需要执行怎么样的处理,没有多余的其他步骤。而原来的方式既使开发人员不希望对一个HttpRequest
进行任何处理,但HttpApplication
仍然会按照管道的设置依次创建HttpModel
-> 激活HttpHandler
-> 处理Session
等。据.net core
团队给出来的性能测试数据来看,Asp.net core
(.net core)相比与原来的Web(.net framework 4.6)程序性能提升了2300%.而
.net core
其实就是保留了上面所说的优势的同时支持跨平台运行。.net core
的系统是可以真正运行在除Windows以外的其他平台的。轻量级、跨平台、模块化是.net core
整体的设计理念,同时也是微软产品理念转变的一个体现。.net core
虽然有千般好,但是我们当前仍然没有直接使用它,因为它现在有一个致使的“缺陷”那就是生态环境,由于.net core
的API已经完全重写,虽然当前已经提供了.net farework
90%以上的API,但是仍然会造成一些开发上的不便,当然这还不是最大的问题,最大的问题在于一些第三方Nuget
包仍然不支持.net core
。这样就会造成一些项目无法直接迁移或是迁移成本太高的问题。如何创建一个
Asp.net core
的项目说了这么多,我们来看一下在创建项目时
Asp.net core
和.net core
有什么不同吧,我们以Vistual studio 2017
上创建项目为例,首先打开VS2017
后点击创建项目->Asp.net core
web应用,这时会弹出模版选择的窗口。
在这个选择窗口中我们可以看到在左上角的那个下拉列表中可以选择.net framework
以及.net core
。当我们选择.net framewrok
时创建出来的项目工程即为asp.net core
。项目创建成功后可以在项目的属性中看到使用的Framework
版本是4.6.2。但是项目文件的组织结构已经和.net core
的项目结构一样了。
Asp.net core
项目的"坑"近期在对新的项目进行性能测试时发现系统的内存占用似乎只能使用到1.5G。经过多次测试以及代码检查终于发现新创建出来的
Asp.net core
的项目默认的目标平台是X86而不是AnyCPU。当尝试在VS中新目标平台改为AnyCPU时发现项目不能运行,抛出异常"无法加载 DLL“libuv”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。",无奈只能将项目的目标平台改为X64,然后发现在开发环境已经一切正常,但是当将代码部署到Azure App Service
上时系统仍然不能访问,异常和上面的相同。最后检查了项目的工程文件(*.proj
)然后发现虽然PlatformTarget
一项中已经改为X64
,但是在PlatformTarget
的属性中Platform
仍然是AnyCPU
,手动修改工程文件将AnyCPU
改为X64
后一切正常
.Net core是微软推出可以跨平台的一种应用程序的开发框架,也是开源托管的计数机软件框架。它能适应Windows , linux以及MacOS操作系统,并且可以在硬件设备,云服务,和嵌入式/IOT方案中进行使用。由于 .NET Core 的开发目标是跨平台的 .NET平台,因此 .NET Core 会包含 .NET Framework 的类库,但与 .NET Framework 不同的是 .NET Core 采用包化 (Packages) 的管理方式,应用程序只需要获取需要的组件即可。.Net Core的源码放在GitHub上,可以由微软官方和社区共同支持
.Net Core是以AOT编译方式为主核心功能,在.Net Core内称为 Core RT 。.Net Core的公共语言开发库(CRL)是 移植 .NET Framework,也就是说.Net Core 的CRL具有.Net Framework中CRL的功能。不过想要使用户.Net Core要去下载.Net Core 的SDK
.Net Core的特性
- 跨平台:可在Windows , MasOS ,Linux上运行
- 部署灵活:(1)Portable applications(便携式应用)这种部署机制和传统的.NET Framework相似,只要目标平台上存在.NET Core Runtime即可。
(2)Self-contained application(自宿主应用)
顾名思义,这种部署机制将应用和运行时共同打包,即便目标平台上没有安装.NET Core Runtime也能正常使用
- 兼容性:通过.NET Standard Library与.NET Framework,Xamarin,Mono兼容
- 开源:能够支持使用MIT和Apache 2开源协议,文档协议遵循CC-BY
在使用Core时,使用WebApi的过程中涉及到的跨域问题,但处理cors的问题是不必再添加Dll文件。ActionAllowOrigin接收请求服务器地址的解析结果。
.NET Core 包括.NET Core Runtime 和 .NET Core SDK:
- .NET Core = 应用运行依赖的 .NET Core Runtime
- .NET Core SDK = 使用.NET Core开发应用.NET Core Runtime 和 SDK+CLI(Software Development Kit/Command Line Interface) 工具
转载于:https://www.cnblogs.com/wodemingtian/p/8458892.html