ASP.NET Implementation of dynamic webapi in core

Time:2021-2-11

1、 Preface

It has been several years since I came into contact with the word dynamic web API. I came into contact with it from the ABP framework. At that time, I was very curious about the ABP technology. After analyzing a wave, I tried to separate one from ABP and use it as an independent component, but later I gave up because I had too much dependence on ABP. More than ten days ago, my friend panda successfully separated this part of the code (I’m doing business with him) from ABP and made a simple demo to throw to me. After so long (it’s too lazy) Finally, after some modification, function addition and encapsulation, it can be used as an independent component. The project is open source in GitHub(https://github.com/dotnetauth/Panda.DynamicWebApi)I hope that those who feel useful can give a star support.

This article only talks about the use, not the principle. The principle will be introduced in detail in the following article.

2、 Introduction

Whether it is the traditional three-tier architecture, DDD classic four tier architecture (DDD Lite), or other architectures with application logic layer (business logic layer), in web application development, our business logic ultimately needs to go through web API To call, we may have a repeated operation here: write business logic > write API to call business logic. Is there a solution to this repetitive operation? After we write business logic, we will automatically generate webapi. Of course, the answer is yes.

Here is an introduction to the protagonist of this articlePanda.DynamicWebApihttps://github.com/dotnetauth/Panda.DynamicWebApi)。 From ABP, it can be used independently and automatically generated for your business logic layer ASP.NET Open source component of core webapi layer. The API generated by it conforms to restful style, and can generate webapi according to the qualified classes. The MVC framework calls the logic directly, and the API documentation is perfectly compatible with swagger.

3、 Use

Here, the application logic layer of DDD classic four tier architecture is used to explain.

1. Preparation

(1) Two projects are established: one is the application logic layer class library project, the other is the webapi host project, ASP.NET Core webapi project

(2) Writing application logic

Define an application logic interface, which should be implemented by all application logic


public interface IApplicationService
{
}

Define a student management logic interface and inherit the application logic interface

public interface IStudentAppService : IApplicationService
{
 /// <summary>
 ///Get students by ID
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 StudentOutput Get(int id);

 /// <summary>
 ///Get all students
 /// </summary>
 /// <returns></returns>
 List<StudentOutput> Get();

 /// <summary>
 ///Update student information
 /// </summary>
 /// <param name="input"></param>
 void Update(UpdateStudentInput input);

 /// <summary>
 ///Update student age
 /// </summary>
 /// <param name="age"></param>
 void UpdateAge(int age);

 /// <summary>
 ///Delete students by ID
 /// </summary>
 /// <param name="id"></param>
 void Delete(int id);

 /// <summary>
 ///Add students
 /// </summary>
 /// <param name="input"></param>
 void Create(CreateStudentInput input);
}

Realize the logical management interface of students

public class StudentAppService: IStudentAppService
{
 /// <summary>
 ///Get students by ID
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 [HttpGet("{id:int}")]
 public StudentOutput Get(int id)
 {
 Return new studentoutput() {id = 1, age = 18, name = Zhang San};
 }

 /// <summary>
 ///Get all students
 /// </summary>
 /// <returns></returns>
 public List<StudentOutput> Get()
 {
 return new List<StudentOutput>()
 {
  New studentoutput() {id = 1, age = 18, name = Zhang San},
  New studentoutput() {id = 2, age = 19, name = Li Si}
 };
 }

 /// <summary>
 ///Update student information
 /// </summary>
 /// <param name="input"></param>
 public void Update(UpdateStudentInput input)
 {
 throw new System.NotImplementedException();
 }

 /// <summary>
 ///Update student age
 /// </summary>
 /// <param name="age"></param>
 [HttpPatch("{id:int}/age")]
 public void UpdateAge(int age)
 {
 throw new System.NotImplementedException();
 }

 /// <summary>
 ///Delete students by ID
 /// </summary>
 /// <param name="id"></param>
 [HttpDelete("{id:int}")]
 public void Delete(int id)
 {
 throw new System.NotImplementedException();
 }

 /// <summary>
 ///Add students
 /// </summary>
 /// <param name="input"></param>
 public void Create(CreateStudentInput input)
 {
 throw new System.NotImplementedException();
 }
}

(3) Configure swagger for the webapi host project.


Install-Package Swashbuckle.AspNetCore -Version 4.0.1

Configuration in startup

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

 services.AddSwaggerGen(options =>
 {
 options.SwaggerDoc ("V1", new info {title = "Xiaochen student management system webapi", version = "V1"});

 options.DocInclusionPredicate((docName, description) => true);

 options.IncludeXmlComments(@"bin\Debug\netcoreapp2.2\Xc.StuMgr.WebApiHost.xml");
 options.IncludeXmlComments(@"bin\Debug\netcoreapp2.2\Xc.StuMgr.Application.xml");
 });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 if (env.IsDevelopment())
 {
 app.UseDeveloperExceptionPage();
 }

 app.UseSwagger();
 app.UseSwaggerUI(c =>
 {
 c.SwaggerEndpoint("/swagger/v1/ swagger.json Xiaochen student management system webapi;
 });

 app.UseMvc();
}

When running, you will directly see the five APIs of the default valuescontroller.

2. Dynamic webapi

Install components for application project through nuget:


Install-Package Panda.DynamicWebApi

Is the interfaceIApplicationServiceinheritIDynamicWebApiAdd features at the same timeDynamicWebApi


[DynamicWebApi]
public interface IApplicationService:IDynamicWebApi
{
}

In the webapi host project, configure dynamic webapi in startup

Startup.cs:

//Add dynamic webapi after addmvc
services.AddDynamicWebApi();

Then open the browser and you will see:

We can see that success is the key to our successStudentAppServiceWebapi is generated and compatible with swagger.

4、 Detailed introduction

After the above introduction, you can see that it is very simple to use. It only needs two steps:

Step 1: inherit for your class (or the interface of the class, the abstract class inherited from the class, which cannot be placed on the parent class of the class except for the first two cases)IDynamicWebApiInterface and add features[DynamicWebApi]

Step 2: register in startup

//Add dynamic webapi after addmvc
services.AddDynamicWebApi();

Because some MVC classes are needed for processing, it must be placed after addmvc. This component has to be checked.

1. Rules

This component adopts convention greater than configuration, so there are several rules in actual use:

(1) In order for a class to generate a dynamic API, two conditions need to be satisfied. One is that the class directly or indirectly implements the APIIDynamicWebApiAt the same time, the class itself or the parent abstract class or the implemented interface has characteristicsDynamicWebApi

(2) Add feature[NonDynamicWebApi]You can make a class or method not generate API,[NonDynamicWebApi]Has the highest priority.

(3) Will be in line with the rules of dynamic API class name suffix deletion, such as: our previousStudentAppServiceThe appservice suffix will be deleted. This rule can be configured dynamically.

(4) API route prefix will be added automatically. By default, it will be added for all APIsapiprefix

(5) The default HTTP verb isPOST, which can be accessed throughHttpGet/HttpPost/HttpDelete wait ASP.NET Core built-in features

(6) Can passHttpGet/HttpPost/HttpDelete And other built-in features to override the default route

(7) By default, HTTP verbs will be set according to your method name, such as create Apple or create generated API verbsPOSTThe cross reference table is as follows. If the cross reference table is hit (case ignored), the verb in the name of the API will be omitted. For example, create Apple will become apple. If it is not in the cross reference table below, the default verb will be usedPOST

Start of method name verb
create POST
add POST
post POST
get GET
find GET
fetch GET
query GET
update PUT
put PUT
delete DELETE
remove DELETE

(8) It is strongly recommended that method names use Pascal case specification to better automatically process API names, and use verbs in the above comparison table. For example:

Add apple – > Add / add apple / create / create apple

Update apple – > Update / update apple

(9)[DynamicWebApi]Because features can be inherited, they are not allowed to be placed on parent classes other than abstract classes and interfaces in order to be misidentified.

2. Configuration

All configurations are in the objectDynamicWebApiOptionsThe explanation is as follows:

Property name Is it necessary explain
DefaultHttpVerb no Default value: post. Default HTTP verb
DefaultAreaName no Default value: empty. Area route name
DefaultApiPrefix no Default value: API. API route prefix
RemoveControllerPostfixes no Default value: appservice / Applicationservice. Suffix to be removed for class name
RemoveActionPostfixes no Default value: async. Suffix to be removed for method name
FormBodyBindingIgnoredTypes no Default value: iformfile. Types that are not bound to parameter lists through MVC.

5、 Troubleshooting

If you encounter problems, you can useIssuesAsk questions.

6、 It’s over

Open source address of the project:https://github.com/dotnetauth/Panda.DynamicWebApiI hope to give a star support

This article demo address:XiaoChen.StudentManagement

ABP:https://github.com/aspnetboilerplate/aspnetboilerplate

This is about ASP.NET This is the article about how to realize the dynamic webapi of core technology, and more about it ASP.NET Core dynamic webapi content, please search the previous articles of developer or continue to browse the related articles below. I hope you can support developer more in the future!

Author: Xiaochen master

Article link: https://www.cnblogs.com/stulzq/p/11007770.html