亲宝软件园·资讯

展开

手把手教你用Abp vnext构建API接口服务

黄明基 人气:2
ABP是一个开源应用程序框架,该项目是ASP.NET Boilerplate Web应用程序框架的下一代,专注于基于ASP.NET Core的Web应用程序开发,也支持开发控制台应用程序。 官方网站:[https://abp.io/](https://abp.io/) 官方文档:[https:/https://img.qb5200.com/download-x/docs.abp.io/](https:/https://img.qb5200.com/download-x/docs.abp.io/) #### 一、使用ABP框架可以快速的搭建一个应用程序,仅需要几步即可完成: ##### 1. 安装ABP CLI ABP CLI是使用ABP框架启动新解决方案的最快方法。如果没有安装ABP CLI,使用命令行窗口安装ABP CLI: ``` dotnet tool install -g Volo.Abp.Cli ``` ##### 2. 在一个空文件夹中使用abp new命令创建您的项目: ``` abp new Acme.BookStore ``` 您可以使用不同级别的名称空间。例如BookStore,Acme.BookStore或Acme.Retail.BookStore。 这样,就已经完成了一个应用程序的搭建。 ![](https://img2020.cnblogs.com/blog/47875/202003/47875-20200317170513627-921172973.png) 然后我们只需要修改一下其他的配置即可运行应用程序,开发人员在这个架构的基础上就可以愉快的撸代码了。 然而,ABP的学习才刚刚开始。ABP放弃了原有MVC的架构,使用了模块化架构,支持微服务,根据DDD模式和原则设计和开发,为应用程序提供分层模型。对于没有微服务开发经验的程序员来说,学习ABP难度比较大。下面我们开始从一个空的web解决方案,一步步搭建API接口服务。 #### 二、用APB基础架构搭建一个用户中心API接口服务 开发环境:Mac Visual Studio Code SDK:dotnet core 3.1 ##### 1. 首先我们创建一个文件夹Lemon.UserCenter,并在终端中打开该文件夹。 使用命令创建一个空的web方案: ``` dotnet new web -o Lemon.UserCenter.HttpApi.Hosting ``` ##### 2. 再使用命令创建其他类库方案: ``` 创建api层 dotnet new classlib -o Lemon.UserCenter.HttpApi 创建应用层 dotnet new classlib -o Lemon.UserCenter.Application 创建领域层 dotnet new classlib -o Lemon.UserCenter.Domain 创建基于EntityFrameworkCore的数据层 dotnet new classlib -o Lemon.UserCenter.EntityFrameworkCore ``` ##### 3. 把所有类库加入解决方案,然后类库间互相引用: ``` 创建解决方案 dotnet new sln 所有类库加入解决方案 dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj 添加项目引用 dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj reference Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj ``` ##### 4. 在领域层新增实体。 领域层添加Volo.Abp.Identity.Domain包引用: ``` dotnet add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj package Volo.Abp.Identity.Domain ``` 创建领域层模块类: ``` using Volo.Abp.Identity; using Volo.Abp.Modularity; namespace Lemon.UserCenter.Domain { [DependsOn(typeof(AbpIdentityDomainModule))] public class UserCenterDomainModule : AbpModule { } } ``` 创建实体类: ``` using System; using Volo.Abp.Domain.Entities; namespace Lemon.UserCenter.Domain { public class UserData : Entity { /// /// 账号 /// /// The account. public string Account { get; set; } /// /// 昵称 /// /// The name of the nike. public string NickName { get; set; } = ""; /// /// 头像 /// /// The head icon. public string HeadIcon { get; set; } = ""; /// /// 手机号码 /// /// The mobile. public string Mobile { get; set; } = ""; /// /// 电子邮箱 /// /// The email. public string Email { get; set; } = ""; /// /// 删除注记 /// /// true if deleted; otherwise, false. public bool Deleted { get; set; } } } ``` ##### 5. 创建数据层 数据层添加引用: ``` dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore.PostgreSQL dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore.Design dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore 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类: ``` using Lemon.UserCenter.Domain; using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; namespace Lemon.UserCenter.EntityFrameworkCore { [ConnectionStringName("Default")] public class UserCenterDbContext : AbpDbContext { public DbSet UserData { get; set; } public UserCenterDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } } ``` 加入UserCenterDbContextFactory类: ``` using System.IO; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; namespace Lemon.UserCenter.EntityFrameworkCore { public class UserCenterDbContextFactory: IDesignTimeDbContextFactory { public UserCenterDbContext CreateDbContext(string[] args) { var configuration = BuildConfiguration(); var builder = new DbContextOptionsBuilder() .UseNpgsql(configuration.GetConnectionString("Default")); return new UserCenterDbContext(builder.Options); } private static IConfigurationRoot BuildConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false); return builder.Build(); } } } ``` 加入appsettings.json配置,用于生成数据迁移代码: ``` { "ConnectionStrings": { "Default": "server=127.0.0.1;port=5432;Database=abp-samples-user-center;uid=postgres;pwd=123456" } } ``` 创建数据层模块类: ``` using Lemon.UserCenter.Domain; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore.PostgreSql; using Volo.Abp.Modularity; namespace Lemon.UserCenter.EntityFrameworkCore { [DependsOn(typeof(UserCenterDomainModule), typeof(AbpEntityFrameworkCoreModule), typeof(AbpEntityFrameworkCorePostgreSqlModule))] public class UserCenterentityFrameworkCoreModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddAbpDbContext(options => { options.AddDefaultRepositories(includeAllEntities: true); }); Configure(options => { options.Configure(ctx => { if (ctx.ExistingConnection != null) { ctx.DbContextOptions.UseNpgsql(ctx.ExistingConnection); } else { ctx.DbContextOptions.UseNpgsql(ctx.ConnectionString); } }); }); #region 自动迁移数据库 context.Services.BuildServiceProvider().GetService().Database.Migrate(); #endregion 自动迁移数据库 } } } ``` 生成数据迁移代码: ``` dotnet ef migrations add InitialCreate --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj ``` 在数据层下生成一个Migrations文件夹,里面的代码就是数据迁移代码,执行以下命令即可在数据库中自动生成数据库表: ``` dotnet ef database update --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj ``` ![](https://img2020.cnblogs.com/blog/47875/202003/47875-20200317170614441-1297050986.png) ##### 6. 在应用层实现具体业务逻辑 应用层添加Volo.Abp.Identity.Application应用: ``` dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj package Volo.Abp.Identity.Application ``` 创建应用层模块类: ``` using Volo.Abp.Modularity; using Volo.Abp.Identity; namespace Lemon.UserCenter.Application { [DependsOn(typeof(AbpIdentityApplicationModule))] public class UserCenterApplicationModule : AbpModule { } } ``` 创建用户接口: ``` using System.Threading.Tasks; using Lemon.UserCenter.Domain; namespace Lemon.UserCenter.Application { public interface IUserService { Task Create(UserData data); } } ``` 实现用户服务: ``` using System; using System.Threading.Tasks; using Lemon.UserCenter.Domain; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Repositories; namespace Lemon.UserCenter.Application { public class UserService : ApplicationService, IUserService { private readonly IRepository _repository; public UserService(IRepository repository) { this._repository = repository; } public async Task Create(UserData data) { return await _repository.InsertAsync(data); } } } ``` ##### 7. 在api层实现webapi控制器 api层添加Volo.Abp.Identity.HttpApi引用: ``` dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj package Volo.Abp.Identity.HttpApi ``` 创建模块类: ``` using Lemon.UserCenter.Application; using Volo.Abp.Identity; using Volo.Abp.Modularity; namespace Lemon.UserCenter.HttpApi { [DependsOn(typeof(AbpIdentityHttpApiModule), typeof(UserCenterApplicationModule))] public class UserCenterHttpApiModule : AbpModule { } } ``` 创建controller: ``` using System.Threading.Tasks; using Lemon.UserCenter.Application; using Lemon.UserCenter.Domain; using Microsoft.AspNetCore.Mvc; using Volo.Abp.AspNetCore.Mvc; namespace Lemon.UserCenter.HttpApi.Controllers { [Route("api/user")] public class UserController : AbpController { private readonly IUserService _userService; public UserController(IUserService userService) { this._userService = userService; } [HttpPost("create")] public async Task Create(UserData data) { var result = await _userService.Create(data); return Json(result); } } } ``` ##### 7. 在api hosting实现项目启动项 添加Volo.Abp.Autofac引用: ``` dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj package Volo.Abp.Autofac ``` 创建模块类 ``` using Lemon.UserCenter.Domain; using Lemon.UserCenter.EntityFrameworkCore; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Hosting; using Volo.Abp; using Volo.Abp.AspNetCore.Mvc; using Volo.Abp.Autofac; using Volo.Abp.Modularity; namespace Lemon.UserCenter.HttpApi.Hosting { [DependsOn(typeof(UserCenterHttpApiModule), typeof(UserCenterDomainModule), typeof(UserCenterentityFrameworkCoreModule), typeof(AbpAspNetCoreMvcModule), typeof(AbpAutofacModule))] public class UserCenterHttpApiHostingModule: AbpModule { public override void OnApplicationInitialization( ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseMvcWithDefaultRouteAndArea(); } } } ``` 修改Program类,新增UseAutofac: ``` using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace Lemon.UserCenter.HttpApi.Hosting { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }).UseAutofac(); } } ``` 修改Startup类: ``` using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Lemon.UserCenter.HttpApi.Hosting { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddApplication(); } public void Configure(IApplicationBuilder app) { app.InitializeApplication(); } } } ``` ##### 8. 运行服务 ``` cd Lemon.UserCenter.HttpApi.Hosting dotnet watch run ``` ##### 9. 最后我们用postman来测试api接口服务是否可以正常使用。 操作如下图: ![](https://img2020.cnblogs.com/blog/47875/202003/47875-20200317170700163-474809096.png) 数据库结果如下: ![](https://img2020.cnblogs.com/blog/47875/202003/47875-20200317170714893-1195611940.png) #### 总结 以上就是接口服务的构建过程,主要参考了ABP CLI生成的项目结构,但是又有所不同。整个分层架构还可以继续优化,这个就见仁见智吧。后续还会继续分享ABP的相关知识,例如identity server 4、缓存、微服务等。 #### GitHub: [https://github.com/huangbenq/abp-samples](https://github.com/huangbenq/abp-samples)

加载全部内容

相关教程
猜你喜欢
用户评论