700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 第二课:ASP.NET Core入门之简单快速搭建ASP.NET Core 3.1项目

第二课:ASP.NET Core入门之简单快速搭建ASP.NET Core 3.1项目

时间:2023-05-07 00:34:38

相关推荐

第二课:ASP.NET Core入门之简单快速搭建ASP.NET Core 3.1项目

一、第一课时创建的项目结构回顾下

下面开始详细讲解创建过程

二、创建Application.Contracts和Dnc.Application.Contracts项目

1、先分别创建应用层Dnc.Application和接口层Dnc.Application.Contracts,框架选用.net standard2.0版本

三、搭建Dnc.Application.Contracts

1、接口层Dnc.Application.Contracts Nuget 搜索UtilsSharp工具类并安装

2、Dnc.Application.Contracts 新建Logins和Users功能服务文件夹和对应的DTOs文件夹,并分别创建接口和Dto出入参

3、IRecordAppService和IUserAppService定义好接口,并分别实现IUnitOfWorkDependency接口,绑定依赖注入关系

using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks;using UtilsSharp.Dependency;using UtilsSharp.Standard;namespace Dnc.Application.Contracts.Logins{/// <summary>/// 登入记录服务/// </summary>public interface IRecordAppService: IUnitOfWorkDependency{/// <summary>/// 获取记录条数/// </summary>/// <returns></returns>ValueTask<BaseResult<int>> GetRecordAsync();}}

using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks;using Dnc.Application.Contracts.Users.DTOs;using UtilsSharp.Dependency;using UtilsSharp.Standard;namespace Dnc.Application.Contracts.Users{/// <summary>/// 用户信息服务/// </summary>public interface IUserAppService : IUnitOfWorkDependency{/// <summary>/// 获取用户信息/// </summary>/// <returns></returns>ValueTask<BaseResult<UserResponse>> GetAsync();}}

using System;using System.Collections.Generic;using System.Text;namespace Dnc.Application.Contracts.Users.DTOs{/// <summary>/// 用户信息/// </summary>public class UserResponse{/// <summary>/// 用户名/// </summary>public string UserName { set; get; }/// <summary>/// 手机号/// </summary>public string Mobile { set; get; }/// <summary>/// 年龄/// </summary>public int Age { set; get; }}}

四、搭建Dnc.Application

1、项目引用Dnc.Application.Contracts项目

2、Dnc.Application 新建Logins和Users功能服务文件夹,并分别创建RecordAppService.cs和UserAppService.cs

3、RecordAppService实现IRecordAppService接口

using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks;using Dnc.Application.Contracts.Logins;using UtilsSharp.Standard;namespace Dnc.Application.Logins{/// <summary>/// 登录记录服务/// </summary>public class RecordAppService: IRecordAppService{/// <summary>/// 获取登录记录条数/// </summary>/// <returns></returns>public async ValueTask<BaseResult<int>> GetRecordAsync(){var result=new BaseResult<int>();//查数据库//if (false)//{// result.SetError("无法连接数据库",8000);// return result;//}await Task.Delay(1000);//模拟执行了1秒result.Result = 101;return result;}}}

4、UserAppService实现IUserAppService接口,并且引用登入记录IRecordAppService

using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks;using Dnc.Application.Contracts.Logins;using Dnc.Application.Contracts.Users;using Dnc.Application.Contracts.Users.DTOs;using UtilsSharp.Standard;namespace Dnc.Application.Users{/// <summary>/// 用户信息服务/// </summary>public class UserAppService: IUserAppService{private readonly IRecordAppService _recordAppService;public UserAppService(IRecordAppService recordAppService){_recordAppService = recordAppService;}/// <summary>/// 获取用户信息/// </summary>/// <returns></returns>public async ValueTask<BaseResult<UserResponse>> GetAsync(){var result=new BaseResult<UserResponse>();//查询数据库.....//if (false)//{// result.SetError("未查询到该条记录");// return result;//}await Task.Delay(1000);//模拟执行1秒var r = await _recordAppService.GetRecordAsync();if (r.Code != 200){result.SetError(r.Msg,r.Code);return result;}result.Result = new UserResponse { UserName = "Agoling", Mobile = "136xxxxxxxx", Age = 10, LoginCount = r.Result};return result;}}}

五、搭建DncHost

1、打开vs,创建.net core新项目:

2、为了方便好记,我们的项目名称就叫Dnc,意思是Dot Net Core 的首写字母,大家可以根据自己的业务取名称,然后选择好项目要放置的路径。

3、选择好项目框架,创建空的 Core 应用程序的空项目模板,大家也可以选择API和Web应用程序(根据项目需求,是前后端分离开接口还是做页面),选择“空”主要是为了不去下载一些没必要的东西,我这边是创建WebApi应用程序。

4、DncHost下面Nuget搜索 UtilsSharp.AspNetCore最新版本2.1.1,安装

5、配置Program.cs

6、配置Startup.cs

①默认的程序

using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.HttpsPolicy;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace DncHost{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();}// 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.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}}

②配置后

using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.HttpsPolicy;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Autofac;using UtilsSharp.AspNetCore;using UtilsSharp.AspNetCore.Interceptor;using UtilsSharp.AspNetCore.Swagger;namespace DncHost{public class Startup:AutofacStartup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){//添加控制器服务services.AddControllers();//添加swagger扩展服务,如果参数不填则用默认的swagger配置AspNetCoreExtensionsConfig.SwaggerDocOptions = new SwaggerDocOptions{Enable = true,ProjectName = "Dnc项目",ProjectDescription = "Dnc项目接口",Groups = new List<SwaggerGroup>{new SwaggerGroup() {GroupName = "Users", Title = "Users接口", Version = "v1.0"},new SwaggerGroup() {GroupName = "Logins", Title = "Logins接口", Version = "v1.0"}}};//添加AspNetCore扩展services.AddAspNetCoreExtensions();}// 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"></param>public override void ConfigureContainer(ContainerBuilder builder){Init<AsyncInterceptor<LoggerAsyncInterceptor>>(builder);//Init(builder);//无aop拦截//Init<LoggerInterceptor>(builder);//仅支持同步的拦截 }}}

Init(builder) 是无Aop拦截,Init<AsyncInterceptor<LoggerAsyncInterceptor>>(builder)是Aop Exception错误日志拦截。会try catch切面收集Service里面的日志。至于AOP是什么大家可以自行百度了解。关于Castle DynamicProxy异步拦截框架,感兴趣的可以看这篇文章:Castle DynamicProxy异步拦截框架

7、大项目都是分功能模块的,所以我们创建个Area,对项目各个功能进行分块

8、分别添加RecordController和UserController两个控制器

9、DncHost项目引用Dnc.Application和Dnc.Application.Contracts项目,控制器调用业务层获取数据,配置好路由和功能模块

using Microsoft.AspNetCore.Mvc;using System.Threading.Tasks;using Dnc.Application.Contracts.Logins;using UtilsSharp.AspNetCore.MVC;using UtilsSharp.Standard;namespace DncHost.Areas.Logins.Controllers{/// <summary>/// 登入记录控制器/// </summary>[ApiExplorerSettings(GroupName = "Logins")][Area("Logins")]public class RecordController : BaseAreaController{private readonly IRecordAppService _recordAppService;public RecordController(IRecordAppService recordAppService){_recordAppService = recordAppService;}/// <summary>/// 获取记录/// </summary>/// <returns></returns>[HttpPost]public async ValueTask<BaseResult<int>> GetRecord(){return await _recordAppService.GetRecordAsync();}}}

using Microsoft.AspNetCore.Mvc;using System.Threading.Tasks;using Dnc.Application.Contracts.Users;using Dnc.Application.Contracts.Users.DTOs;using UtilsSharp.AspNetCore.MVC;using UtilsSharp.Standard;namespace DncHost.Areas.Users.Controllers{/// <summary>/// 用户控制器/// </summary>[ApiExplorerSettings(GroupName = "Users")][Area("Users")]public class UserController : BaseAreaController{private readonly IUserAppService _userAppService;public UserController(IUserAppService userAppService){_userAppService = userAppService;}/// <summary>/// 获取用户信息/// </summary>/// <returns></returns>[HttpPost]public async ValueTask<BaseResult<UserResponse>> Get(){return await _userAppService.GetAsync();}}}

10、移除一些自带的程序,包含Controllers里面的WeatherForecastController

11、修改默认启动

12、把DncHost设为启动项目

13、启动项目,即可看到项目swagger接口

注意:若swagger配置是写在appsettings.json里面,有中文内容的话,页面会出现中文乱码,把appsettings.json 改为utf-8格式即可:

14、由于没有注释,所以大家可以按下面的方法,即可显示出注释。DncHost右键属性->XML文档文件打勾

15、测试数据

16、添加日志,Log.Application添加nuget包UtilsSharp.Logger

17、UtilsSharp.Logger安装完成后就可以写日志了

18、DncHost引用UtilsSharp.Logger.Config日志配置包

19、日志有两种写入方式,一种是接口方式,另一种是文件方式,配置已经都配置好了

20、运行下接口试下,日志就产生了

21、以上是先简单模拟数据走通依赖注入和swagger功能,数据库、Redis、RabbitMq这块的使用后面再单独讲

本项目源代码:/agoling/dnc

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。