ABP是一个开源应用程序框架,该项目是ASP.NET Boilerplate Web应用程序框架的下一代,专注于基于ASP.NET Core的Web应用程序开发,也支持开发控制台应用程序。

官方网站:https://abp.io/

官方文档:https://docs.abp.io/

一、使用ABP框架可以快速的搭建一个应用程序,仅需要几步即可完成:

1. 安装ABP CLI

ABP CLI是使用ABP框架启动新解决方案的最快方法。如果没有安装ABP CLI,使用命令行窗口安装ABP CLI:

  1. dotnet tool install -g Volo.Abp.Cli

2. 在一个空文件夹中使用abp new命令创建您的项目:

  1. abp new Acme.BookStore

您可以使用不同级别的名称空间。例如BookStore,Acme.BookStore或Acme.Retail.BookStore。

这样,就已经完成了一个应用程序的搭建。

然后我们只需要修改一下其他的配置即可运行应用程序,开发人员在这个架构的基础上就可以愉快的撸代码了。

然而,ABP的学习才刚刚开始。ABP放弃了原有MVC的架构,使用了模块化架构,支持微服务,根据DDD模式和原则设计和开发,为应用程序提供分层模型。对于没有微服务开发经验的程序员来说,学习ABP难度比较大。下面我们开始从一个空的web解决方案,一步步搭建API接口服务。

二、用APB基础架构搭建一个用户中心API接口服务

开发环境:Mac Visual Studio Code

SDK:dotnet core 3.1

1. 首先我们创建一个文件夹Lemon.UserCenter,并在终端中打开该文件夹。

使用命令创建一个空的web方案:

  1. dotnet new web -o Lemon.UserCenter.HttpApi.Hosting

2. 再使用命令创建其他类库方案:

  1. 创建api
  2. dotnet new classlib -o Lemon.UserCenter.HttpApi
  3. 创建应用层
  4. dotnet new classlib -o Lemon.UserCenter.Application
  5. 创建领域层
  6. dotnet new classlib -o Lemon.UserCenter.Domain
  7. 创建基于EntityFrameworkCore的数据层
  8. dotnet new classlib -o Lemon.UserCenter.EntityFrameworkCore

3. 把所有类库加入解决方案,然后类库间互相引用:

  1. 创建解决方案
  2. dotnet new sln
  3. 所有类库加入解决方案
  4. dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj
  5. dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj
  6. dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj
  7. dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj
  8. dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj
  9. 添加项目引用
  10. dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj
  11. dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj
  12. dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj reference Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj
  13. dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj
  14. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj

4. 在领域层新增实体。

领域层添加Volo.Abp.Identity.Domain包引用:

  1. dotnet add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj package Volo.Abp.Identity.Domain

创建领域层模块类:

  1. using Volo.Abp.Identity;
  2. using Volo.Abp.Modularity;
  3. namespace Lemon.UserCenter.Domain
  4. {
  5. [DependsOn(typeof(AbpIdentityDomainModule))]
  6. public class UserCenterDomainModule : AbpModule
  7. {
  8. }
  9. }

创建实体类:

  1. using System;
  2. using Volo.Abp.Domain.Entities;
  3. namespace Lemon.UserCenter.Domain
  4. {
  5. public class UserData : Entity<Guid>
  6. {
  7. /// <summary>
  8. /// 账号
  9. /// </summary>
  10. /// <value>The account.</value>
  11. public string Account { get; set; }
  12. /// <summary>
  13. /// 昵称
  14. /// </summary>
  15. /// <value>The name of the nike.</value>
  16. public string NickName { get; set; } = "";
  17. /// <summary>
  18. /// 头像
  19. /// </summary>
  20. /// <value>The head icon.</value>
  21. public string HeadIcon { get; set; } = "";
  22. /// <summary>
  23. /// 手机号码
  24. /// </summary>
  25. /// <value>The mobile.</value>
  26. public string Mobile { get; set; } = "";
  27. /// <summary>
  28. /// 电子邮箱
  29. /// </summary>
  30. /// <value>The email.</value>
  31. public string Email { get; set; } = "";
  32. /// <summary>
  33. /// 删除注记
  34. /// </summary>
  35. /// <value><c>true</c> if deleted; otherwise, <c>false</c>.</value>
  36. public bool Deleted { get; set; }
  37. }
  38. }

5. 创建数据层

数据层添加引用:

  1. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore
  2. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore.PostgreSQL
  3. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore.Design
  4. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore
  5. dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore.Relational

在这里我们使用的是PostgreSQL数据库,所以引用了Volo.Abp.EntityFrameworkCore.PostgreSQL,如果使用的是MySQL,就要引用Volo.Abp.EntityFrameworkCore.MySQL,如果使用的是sqlserver,就要引用Volo.Abp.EntityFrameworkCore.SQLServer。

加入UserCenterDbContext类:

  1. using Lemon.UserCenter.Domain;
  2. using Microsoft.EntityFrameworkCore;
  3. using Volo.Abp.Data;
  4. using Volo.Abp.EntityFrameworkCore;
  5. namespace Lemon.UserCenter.EntityFrameworkCore
  6. {
  7. [ConnectionStringName("Default")]
  8. public class UserCenterDbContext : AbpDbContext<UserCenterDbContext>
  9. {
  10. public DbSet<UserData> UserData { get; set; }
  11. public UserCenterDbContext(DbContextOptions<UserCenterDbContext> options)
  12. : base(options)
  13. {
  14. }
  15. protected override void OnModelCreating(ModelBuilder builder)
  16. {
  17. base.OnModelCreating(builder);
  18. }
  19. }
  20. }

加入UserCenterDbContextFactory类:

  1. using System.IO;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.EntityFrameworkCore.Design;
  4. using Microsoft.Extensions.Configuration;
  5. namespace Lemon.UserCenter.EntityFrameworkCore
  6. {
  7. public class UserCenterDbContextFactory: IDesignTimeDbContextFactory<UserCenterDbContext>
  8. {
  9. public UserCenterDbContext CreateDbContext(string[] args)
  10. {
  11. var configuration = BuildConfiguration();
  12. var builder = new DbContextOptionsBuilder<UserCenterDbContext>()
  13. .UseNpgsql(configuration.GetConnectionString("Default"));
  14. return new UserCenterDbContext(builder.Options);
  15. }
  16. private static IConfigurationRoot BuildConfiguration()
  17. {
  18. var builder = new ConfigurationBuilder()
  19. .SetBasePath(Directory.GetCurrentDirectory())
  20. .AddJsonFile("appsettings.json", optional: false);
  21. return builder.Build();
  22. }
  23. }
  24. }

加入appsettings.json配置,用于生成数据迁移代码:

  1. {
  2. "ConnectionStrings": {
  3. "Default": "server=127.0.0.1;port=5432;Database=abp-samples-user-center;uid=postgres;pwd=123456"
  4. }
  5. }

创建数据层模块类:

  1. using Lemon.UserCenter.Domain;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Volo.Abp.EntityFrameworkCore;
  5. using Volo.Abp.EntityFrameworkCore.PostgreSql;
  6. using Volo.Abp.Modularity;
  7. namespace Lemon.UserCenter.EntityFrameworkCore
  8. {
  9. [DependsOn(typeof(UserCenterDomainModule),
  10. typeof(AbpEntityFrameworkCoreModule),
  11. typeof(AbpEntityFrameworkCorePostgreSqlModule))]
  12. public class UserCenterentityFrameworkCoreModule : AbpModule
  13. {
  14. public override void ConfigureServices(ServiceConfigurationContext context)
  15. {
  16. context.Services.AddAbpDbContext<UserCenterDbContext>(options => {
  17. options.AddDefaultRepositories(includeAllEntities: true);
  18. });
  19. Configure<AbpDbContextOptions>(options =>
  20. {
  21. options.Configure(ctx =>
  22. {
  23. if (ctx.ExistingConnection != null)
  24. {
  25. ctx.DbContextOptions.UseNpgsql(ctx.ExistingConnection);
  26. }
  27. else
  28. {
  29. ctx.DbContextOptions.UseNpgsql(ctx.ConnectionString);
  30. }
  31. });
  32. });
  33. #region 自动迁移数据库
  34. context.Services.BuildServiceProvider().GetService<UserCenterDbContext>().Database.Migrate();
  35. #endregion 自动迁移数据库
  36. }
  37. }
  38. }

生成数据迁移代码:

  1. dotnet ef migrations add InitialCreate --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj

在数据层下生成一个Migrations文件夹,里面的代码就是数据迁移代码,执行以下命令即可在数据库中自动生成数据库表:

  1. dotnet ef database update --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj

6. 在应用层实现具体业务逻辑

应用层添加Volo.Abp.Identity.Application应用:

  1. dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj package Volo.Abp.Identity.Application

创建应用层模块类:

  1. using Volo.Abp.Modularity;
  2. using Volo.Abp.Identity;
  3. namespace Lemon.UserCenter.Application
  4. {
  5. [DependsOn(typeof(AbpIdentityApplicationModule))]
  6. public class UserCenterApplicationModule : AbpModule
  7. {
  8. }
  9. }

创建用户接口:

  1. using System.Threading.Tasks;
  2. using Lemon.UserCenter.Domain;
  3. namespace Lemon.UserCenter.Application
  4. {
  5. public interface IUserService
  6. {
  7. Task<UserData> Create(UserData data);
  8. }
  9. }

实现用户服务:

  1. using System;
  2. using System.Threading.Tasks;
  3. using Lemon.UserCenter.Domain;
  4. using Volo.Abp.Application.Services;
  5. using Volo.Abp.Domain.Repositories;
  6. namespace Lemon.UserCenter.Application
  7. {
  8. public class UserService : ApplicationService, IUserService
  9. {
  10. private readonly IRepository<UserData, Guid> _repository;
  11. public UserService(IRepository<UserData, Guid> repository)
  12. {
  13. this._repository = repository;
  14. }
  15. public async Task<UserData> Create(UserData data)
  16. {
  17. return await _repository.InsertAsync(data);
  18. }
  19. }
  20. }

7. 在api层实现webapi控制器

api层添加Volo.Abp.Identity.HttpApi引用:

  1. dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj package Volo.Abp.Identity.HttpApi

创建模块类:

  1. using Lemon.UserCenter.Application;
  2. using Volo.Abp.Identity;
  3. using Volo.Abp.Modularity;
  4. namespace Lemon.UserCenter.HttpApi
  5. {
  6. [DependsOn(typeof(AbpIdentityHttpApiModule),
  7. typeof(UserCenterApplicationModule))]
  8. public class UserCenterHttpApiModule : AbpModule
  9. {
  10. }
  11. }

创建controller:

  1. using System.Threading.Tasks;
  2. using Lemon.UserCenter.Application;
  3. using Lemon.UserCenter.Domain;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Volo.Abp.AspNetCore.Mvc;
  6. namespace Lemon.UserCenter.HttpApi.Controllers
  7. {
  8. [Route("api/user")]
  9. public class UserController : AbpController
  10. {
  11. private readonly IUserService _userService;
  12. public UserController(IUserService userService)
  13. {
  14. this._userService = userService;
  15. }
  16. [HttpPost("create")]
  17. public async Task<IActionResult> Create(UserData data)
  18. {
  19. var result = await _userService.Create(data);
  20. return Json(result);
  21. }
  22. }
  23. }

7. 在api hosting实现项目启动项

添加Volo.Abp.Autofac引用:

  1. dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj package Volo.Abp.Autofac

创建模块类

  1. using Lemon.UserCenter.Domain;
  2. using Lemon.UserCenter.EntityFrameworkCore;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.Extensions.Hosting;
  5. using Volo.Abp;
  6. using Volo.Abp.AspNetCore.Mvc;
  7. using Volo.Abp.Autofac;
  8. using Volo.Abp.Modularity;
  9. namespace Lemon.UserCenter.HttpApi.Hosting
  10. {
  11. [DependsOn(typeof(UserCenterHttpApiModule),
  12. typeof(UserCenterDomainModule),
  13. typeof(UserCenterentityFrameworkCoreModule),
  14. typeof(AbpAspNetCoreMvcModule),
  15. typeof(AbpAutofacModule))]
  16. public class UserCenterHttpApiHostingModule: AbpModule
  17. {
  18. public override void OnApplicationInitialization(
  19. ApplicationInitializationContext context)
  20. {
  21. var app = context.GetApplicationBuilder();
  22. var env = context.GetEnvironment();
  23. if (env.IsDevelopment())
  24. {
  25. app.UseDeveloperExceptionPage();
  26. }
  27. else
  28. {
  29. app.UseExceptionHandler("/Error");
  30. }
  31. app.UseStaticFiles();
  32. app.UseRouting();
  33. app.UseMvcWithDefaultRouteAndArea();
  34. }
  35. }
  36. }

修改Program类,新增UseAutofac:

  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.Extensions.Hosting;
  3. namespace Lemon.UserCenter.HttpApi.Hosting
  4. {
  5. public class Program
  6. {
  7. public static void Main(string[] args)
  8. {
  9. CreateHostBuilder(args).Build().Run();
  10. }
  11. public static IHostBuilder CreateHostBuilder(string[] args) =>
  12. Host.CreateDefaultBuilder(args)
  13. .ConfigureWebHostDefaults(webBuilder =>
  14. {
  15. webBuilder.UseStartup<Startup>();
  16. }).UseAutofac();
  17. }
  18. }

修改Startup类:

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.Extensions.DependencyInjection;
  3. namespace Lemon.UserCenter.HttpApi.Hosting
  4. {
  5. public class Startup
  6. {
  7. public void ConfigureServices(IServiceCollection services)
  8. {
  9. services.AddApplication<UserCenterHttpApiHostingModule>();
  10. }
  11. public void Configure(IApplicationBuilder app)
  12. {
  13. app.InitializeApplication();
  14. }
  15. }
  16. }

8. 运行服务

  1. cd Lemon.UserCenter.HttpApi.Hosting
  2. dotnet watch run

9. 最后我们用postman来测试api接口服务是否可以正常使用。

操作如下图:

数据库结果如下:

总结

以上就是接口服务的构建过程,主要参考了ABP CLI生成的项目结构,但是又有所不同。整个分层架构还可以继续优化,这个就见仁见智吧。后续还会继续分享ABP的相关知识,例如identity server 4、缓存、微服务等。

GitHub: https://github.com/huangbenq/abp-samples

手把手教你用Abp vnext构建API接口服务的更多相关文章

  1. ASP.NET WebAPI构建API接口服务实战演练

    一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...

  2. ASP.NET Core WebApi构建API接口服务实战演练

    一.ASP.NET Core WebApi课程介绍 人生苦短,我用.NET Core!提到Api接口,一般会想到以前用到的WebService和WCF服务,这三个技术都是用来创建服务接口,只不过Web ...

  3. 使用Swoole 构建API接口服务

    网上类似的文章已经很多了,我也是刚入门.从头开始学习.所以如果重复写文章阐释,反而会浪费时间,于是就自己动手构建了一个demo,使用swoole 的TCP 服务器接受TCP客户端的发来的http请求, ...

  4. 亿级用户下的新浪微博平台架构 前端机(提供 API 接口服务),队列机(处理上行业务逻辑,主要是数据写入),存储(mc、mysql、mcq、redis 、HBase等)

    https://mp.weixin.qq.com/s/f319mm6QsetwxntvSXpKxg 亿级用户下的新浪微博平台架构 炼数成金前沿推荐 2014-12-04 序言 新浪微博在2014年3月 ...

  5. API接口服务端

    <?php /** * API接口服务端 * * */ require 'mysql_class.php'; header('Content-Type:text/html;charset=utf ...

  6. 使用Abp vnext构建基于Duende.IdentityServer的统一授权中心(一)

    原来看到很多示例都是基于IdentityServer4的统一授权中心,但是IdentityServer4维护到2022年就不再进行更新维护了,所以我选择了它的升级版Duende.IdentitySer ...

  7. 怎样提供一个好的移动API接口服务/从零到一[开发篇]

    引语:现在互联网那么热,你手里没几个APP都不好意思跟别人打招呼!但是,难道APP就是全能的神吗?答案是否定的,除了优雅的APP前端展示,其实核心还是服务器端.数据的保存.查询.消息的推送,无不是在服 ...

  8. 四十五:漏洞发现-API接口服务之漏洞探针类型利用修复

    接口服务类安全测试 根据前期信息收集针对目标端口服务类探针后进行的安全测试,主要涉及攻击方法:口令安全,WEB类漏洞,版本漏洞等,其中产生的危害可大可小,属于端口服务/第三方服务类安全测试.一般在已知 ...

  9. 手把手教你学Numpy,这些api不容错过

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Numpy专题的第5篇文章,我们来继续学习Numpy当中一些常用的数学和统计函数. 基本统计方法 在日常的工作当中,我们经常需要通过一 ...

随机推荐

  1. Jumpserver 一键部署(支持离线安装)

    1.教程介绍1.1::通过本教程起到抛砖引玉效果,希望各位喜爱Jumpserver堡垒机的朋友受益良多. 1.2::以下提供的任何软件仅供学习交流使用. 2.下载链接2.1::centos_1810最 ...

  2. @Value默认值填null

    @Value("${topology.position.spout.maxpending:#{null}}") private Integer spoutMaxPending; @ ...

  3. MOOC(7)- case依赖、读取json配置文件进行多个接口请求-完整的测试类,含依赖测试(15)

    ddt.依赖测试.断言.测试数据写回 # -*- coding: utf-8 -*- # @Time : 2020/2/12 23:07 # @File : test_class_15.py # @A ...

  4. DB2数据库多行一列转换成 一行一列

    在db2中遇到多行一列转为一行一列的需求时,用db2函数 LISTAGG可以实现该功能.语法如下: SELECT   [分组的字段 ] , LISTAGG([需要聚合的字段名], ',')   FRO ...

  5. scarce|component|

    ADJ-GRADED 缺乏的;不足的;供不应求的If something is scarce, there is not enough of it. Food was scarce and expen ...

  6. axios 传对象(JavaBean)到后台

    //user对象 let user = JSON.stringify({ userAccountNumber: own.userName, userPassword: own.userPassword ...

  7. C++二级指针和指针引用传参

    前提 一级指针和引用 已经清晰一级指针和引用. 可参考:指针和引用与及指针常量和常量指针 或查阅其他资料. 一级指针和二级指针 个人觉得文字描述比较难读懂,直接看代码运行结果分析好些,如果想看文字分析 ...

  8. Rails (栈)

    题目链接:https://vjudge.net/problem/UVA-514 题目大意: 有A,B,C三个火车停靠点,火车最初停在A站,给你一个序列,问你能不能通过中转站C到达B站,火车从A站进入到 ...

  9. canvas基本

    基本 支持ie 9+,firefox,opera,chrome,safari html: <canvas id="fir_canvas" width="400&qu ...

  10. JavaScript闭包、Object对象

    JavaScript闭包 定义:闭包指一个拥有许多变量和绑定这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分. function a(){ var i=0; function ...