第二课: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、打开vs2019,创建.net core新项目:

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

3、选择好项目框架,创建空的Asp.NET 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这块的使用后面再单独讲

本项目源代码:https://github.com/agoling/dnc

  • 7
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值