ABP Framework-My first web API

Source: Internet
Author: User
Tags app service connectionstrings

We have an impression of what ABP is, what we can do and what we do. So next we'll start using the ABP framework to quickly develop an API, and you'll find out how convenient it is to use the ABP framework and actually feel its allure.

Environmental requirements
    • Visual Studio 2017
    • SQL Server
    • . Net Core SDK
Create an application

We use ABP templates to create applications, Access http://www.aspnetboilerplate.com/Templates, and you will see the following pages

    • Select the options shown in the reference
    • Enter the project name, I am here "abptraining"
    • Enter the verification code

Click "Create Project", then we will get a project source code compression package Abptraining.zip from the ABP template website. Extracting the Abptraining.zip will get the original project source code.

Running the application
    • Go to unzip directory, click Aspnet-core/abptraining.sln, open Solution
    • To create a database in a local SQL Server DB instance Abptrainingdb
    • Locate Abptraining.web.host/appsettings.json and modify the database connection (ConnectionStrings) based on your local environment

       "ConnectionStrings": {    "Default": "Server=localhost; Database=AbpTrainingDb; Trusted_Connection=True;"}
    • To create an initial database by using a database migration script
      • In Visual Studio, select Tools, NuGet Package Manager, Package Manager console
      • Set AbpTraining.Web.Host as Startup Project
      • Setting Abptraining.entityframeworkcore as the default item in the Package Manager console
      • The Package Manager console executes the command Update-database-verbos, waits for the command to complete successfully, completes the synchronization of the database
    • Run AbpTraining.Web.Host, the Swagger API page will appear, the program runs successfully

My first API1. API features

Function: Search product information according to product name

2. Create a commodity entity

Abptraining.core\products\product.cs

using Abp.Domain.Entities.Auditing;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;namespace AbpTraining.Products{    //可以显示的指定表名,不指定默认是实体名+s    [Table("Product")]    public class Product : FullAuditedEntity<long>    {        [Required]        [StringLength(128)]        public string Name { get; set; }        public decimal Price { get; set; }    }}
    • [Table ("Product")] Displays the table name corresponding to the specified entity and, if not specified, the default class name +s
    • Fullauditedentity
    • [Required] Specifies that the field is required and does not specify that the field can be empty
    • [Stringlength (128)] Specifies the maximum length of a field is 128
3. Create a product area Domainservice

Abptraining.core\products\productdomainservice.cs

Using abp.domain.repositories;using abp.domain.services;using system.threading.tasks;using System.Linq;using Abp.UI ; Using Microsoft.entityframeworkcore;namespace abptraining.products{public class Productdomainservice:        DomainService {private ReadOnly irepository<product, long> _productrepository; Public Productdomainservice (irepository<product, long> productrepository) {_productrepository = P        Roductrepository; Public Async task<product> Getproductbyname (string name) {var query = from P in _product            Repository.getall () where p.name = = Name Select P; var product = await query.            Firstordefaultasync ();            if (product = null) {throw new Userfriendlyexception ($ "commodity ({name}) does not exist"); } if (product.  Price < 0) {throw new Userfriendlyexception ($ "commodity ({name}) is less than 0, please check");          } return product; }    }}
    • Domain Services to inherit Domainservice
    • _productrepository Data Warehousing Direct Dependency Injection
    • Using async await an asynchronous programming model
    • querying data using LINQ to SQL
    • If you want to return a business error message to the client, use the Userfriendlyexception
4. Create a product ApplicationService4.1 define a DTO

Abptraining.application\products\dto\productdto

using Abp.AutoMapper;namespace AbpTraining.Products.Dto{    [AutoMapFrom(typeof(Product))]    public class ProductDto    {        public string Name { get; set; }        public decimal Price { get; set; }    }}
    • The Automapfrom attribute indicates which class can be automatically mapped to the current class, so there is no need to manually convert the entity time

Abptraining.application\products\dto\getproductbynameinput

using System.ComponentModel.DataAnnotations;namespace AbpTraining.Products.Dto{    public class GetProductByNameInput    {        [Required]        public string Name { get; set; }    }}
    • [Required]-this attribute is available in the input object, and the ABP automatically verifies this field of request

Mysoft.rdc.application\products\dto\getproductbynameoutput

namespace AbpTraining.Products.Dto{    public  class GetProductByNameOutput : ProductDto    {    }}
4.2 Defining the Applicationservice interface

Abptraining.application\products\iproductappservice.cs

using Abp.Application.Services;using AbpTraining.Products.Dto;using System.Threading.Tasks;namespace AbpTraining.Products{    public interface IProductAppService : IApplicationService    {        Task<GetProductByNameOutput> GetProductByName(GetProductByNameInput input);    }}
    • Application service interface to inherit Iapplicationservice
4.3 Product applicationservice Realization

Abptraining.application\products\productappservice.cs

using System.Threading.Tasks;namespace AbpTraining.Products.Dto{    public class ProductAppService : AbpTrainingAppServiceBase, IProductAppService    {        private readonly ProductDomainService _productDomainService;        public ProductAppService(ProductDomainService productDomainService)        {            _productDomainService = productDomainService;        }        public async Task<GetProductByNameOutput> GetProductByName(GetProductByNameInput input)        {            //1.将input dto转换为domain obj            //2.调用doamin service            var item = await _productDomainService.GetProductByName(input.Name);            //call other doamin serivce            //3.将domain obj转换为output dto            var output = ObjectMapper.Map<GetProductByNameOutput>(item);            return output;        }    }}
    • App service implementations to inherit Abptrainingappservicebase
5. Database 5.1 Database Entity mappings

Add the following code snippet in Abptraining.entityframeworkcore\entityframeworkcore\abptrainingdbcontext.cs

public DbSet<Product> Products { get; set; }
5.2 Generating migration files

In the Package Manager console, execute the following command to generate the migration script file

Add-Migration AddProduct -Verbos
    • After execution, you will see the newly generated script file under Abptraining.entityframeworkcore\migrations, and the file name I generated this time is 20180405043514_addproduct.cs (There will be a timestamp prefix, each time will be different)
5.3 Updating the database

In the Package Manager console, execute the following command to synchronize the new entity with the database

Update-Database -Verbos
    • After execution completes, you will see a new table in the database product
6. Running the service, testing

Set AbpTraining.Web.Host as the startup project, run directly in Visual Studio, and find it in the Swagger API list/api/services/app/product/getproductbyname You can start testing.

In this case, our first API has been successfully completed.

ABP Framework-My first web API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.