In many of the Web API projects that were developed earlier, for convenience and rapid development, the controller of the entire Web API was placed in the controllers directory of the base directory, but as the business became more complex, the files in the controllers directory increased quickly, were difficult to manage, And if you have different business modules with duplicate controller names, you need to avoid them as much as possible. The role of the introduction area is to separate the controller according to different business modules, convenient management, and the name of the controller can be duplicate.
1. Web API Project introduces area for classification
Area in the project can be called the region, each zone represents the different functional modules of the application, area so that each function module has its own folder, the folder has its own controller, view and model, but for management also increased a certain degree of difficulty. If it is a Web API project, we can remove unnecessary directories and simplify the management of the directory.
The introduction of area can be our different business modules can be the same name, and the various business modules are more convenient to manage, in the original Web API project, their directory is such.
Although we classify their directories, they are stored in a namespace.
namespace Mywebapi.controllers
This use, although there is no problem, but there are some drawbacks, so the introduction of the area of different business modules to manage the controller to achieve our purpose of classification management.
Before introducing area, our API path is as follows
Http://localhost:9001/api/User
After the introduction of area, we put the general Rights Management, dictionary management and other basic modules into the area of the framework, then this time the API path and the specific area related, the address has become as follows:
Http://localhost:9001/api/Framework/User
Let's take a look at the specific project directory where the controller's directory is shown below when using area in the Web API project.
In addition to having different controllers in different areas, it also adds a * * AreaRegistration.cs files, such as the corresponding framework area, have a FrameworkAreaRegistration.cs file
This corresponds to the following controller, whose namespace is shown below.
namespace WebAPI.Areas.Framework.Controllers
2. Path mapping of the WEB API project to the area controller
The section above describes the classification management of Web API controllers using area, and describes the differences in the location of the controller, the namespace, the URL of the Web API, and so on. This way, if we want to parse the corresponding address of the Web API, then we need to do some processing, otherwise the corresponding controller can not be found, resulting in an error message.
First we need to modify the configuration information inside the Web API Webapiconfig, as shown below.
The default Web API mappings are specified above and the results are only output in JSON format (remove XML output).
In order to implement the address processing of API in different area, we first design a base class, then let different area register class inherit it, it is convenient to unify processing.
Where the base class area registration class's Customarearegistration class code is shown below.
With the above base class mapping Registerarea function, we only need to set the corresponding AreaName base class in the subclass to implement the correct mapping API path processing for different area subclasses.
/// <SUMMARY> /// /// </summary> public class Span style= "color: #000000;" > frameworkarearegistration:customarearegistration { public override string AreaName { get { return " framework " ; } }}
Of course, in order to properly parse the URL of the Web API controller for the area and get the object belonging to the action, controller, and corresponding namespace, you also need to add a line of code to the Global.asa.cs, as shown below.
// support for the area of the Web API GlobalConfiguration.Configuration.Services.Replace (typeof(ihttpcontrollerselector), new Areahttpcontrollerselector (globalconfiguration.configuration));
Where Areahttpcontrollerselector is our custom HTTP controller address resolver, we need to extract the specific controller, area name, assembly type and so on according to our address, so that the corresponding parser can be built easily.
Privatehttpcontrollerdescriptor Getapicontroller (httprequestmessage request) {varControllername =Base. Getcontrollername (Request); varAreaName =Getareaname (Request); if(string. IsNullOrEmpty (AreaName)) {return NULL; } varType =Getcontrollertypebyarea (AreaName, controllername); if(Type = =NULL) { return NULL; } return NewHttpcontrollerdescriptor (_configuration, controllername, type);}
With these basic management, we can define the area we need, and then build the controller interface in the specific business category.
3. Web API calls on the client interface
All Web API addresses are related to specific area, such as the dictionary module under the Framework business, and the address of their Web API configuration is shown below.
<!--dictionary Web API module Configuration--
<add key= "Dicttype" value= "Http://localhost:27206/api/Framework/DictType"/>
<add key= "Dictdata" value= "Http://localhost:27206/api/Framework/DictData"/>
<add key= "Corpdictdata" value= "Http://localhost:27206/api/Framework/CorpDictData"/>
<add key= "City" value= "Http://localhost:27206/api/Framework/City"/>
<add key= "District" value= "Http://localhost:27206/api/Framework/District"/>
<add key= "province" value= "Http://localhost:27206/api/Framework/Province"/>
<add key= "Userparameter" value= "Http://localhost:27206/api/Framework/UserParameter"/>
We are in the client, only need to encapsulate the Web API, this part can use the Database2sharp Code generation tool for unified generation, all the inheritance relationship is handled uniformly, all we do is to do the new interface processing.
For example, for the processing of the dictionary module Dictdata, its wrapper class for the Web API is shown below.
/// <summary> /// Dictdata, API service-based facade interface implementation class /// </summary> Public class Dictdatacaller:baseapiservice<dictdatainfo>, Idictdataservice
This base class, by default, encapsulates the General data Table business Web API interface mode of additions and deletions and a variety of complex interface processing.
If you have a generic web API (non-data-table business), you only need to inherit the base class to make adjustments.
/// <summary> /// API Service-based facade interface implementation class /// </summary> Public class Testcaller:normalapiservice, Itestservice
This Normalapiservice base class, by default just encapsulates the token and signature of the read processing, no special business interface, specific interface we to implement processing.
For the WEBAPI client call, we basically need to construct the corresponding URL, and then pass some parameters via get pass or post, and read the HTML result, parse it into corresponding type data, as shown in the code below.
/// <summary>///get the corresponding dictionary record based on the dictionary type name/// </summary>/// <param name= "Dicttypename" >Dictionary type name</param>/// <returns></returns> PublicList<dictdatainfo> Findbydicttype (stringdicttypename) { varAction =System.Reflection.MethodBase.GetCurrentMethod (). Name; stringurl = Gettokenurl (action) +string. Format ("&dicttypename={0}", Dicttypename); List<DictDataInfo> result = jsonhelper<list<dictdatainfo>>. Convertjson (URL); returnresult;}
Through the Gettokenurl (action) function to obtain the corresponding URL address, due to the passing of a parameter, the interface here does not have data modification, is a GET method to submit parameter data, so the parameter appended to the URL.
That is, the following code implements the construction of the full Web API address.
String url = Gettokenurl (action) + string. Format ("&dicttypename={0}", Dicttypename);
Once these URLs have been built, we can get the results of the corresponding Web API and sequence the serial numbers to specific objects. As shown in the following code.
list<dictdatainfo> result = Jsonhelper<list<dictdatainfo>>. Convertjson (URL);
For a design article on the Web API interface, refer to my essay.
- Web API Interface Design Experience Summary
- WEB API Application Architecture Design Analysis (1)
- WEB API Application Architecture Design Analysis (2)
For the use of specific Web API interfaces, you can refer to the essay:
- Application of WEB API application architecture in WinForm Hybrid Framework (1)
- Application of WEB API application architecture in WinForm Hybrid Framework (2)--Processing of custom exception results
- Application of WEB API application architecture in WinForm Hybrid Framework (3) process decomposition of--winfrom interface call WEBAPI
- Application of WEB API application architecture in WinForm Hybrid Framework (4)--quickly develop a full suite of applications with code generation tools
- Application of WEB API application architecture in WinForm Hybrid Framework (5)--how system-level dictionaries coexist with company-level dictionaries
With the above encapsulation processing, the client-specific code is shown below for the Web API interface invocation of the business table.
var dicttype = callerfactory<idicttypeservice>. Instance.gettree (); Console.WriteLine (Dicttype.tojson ()); var dictdata = callerfactory<idictdataservice>. Instance.getalldict (); Console.WriteLine (Dictdata.tojson ());
If you call a Web API interface for a non-data table business, the code that uses the client is as follows.
var testaction = callerfactory<itestservice>. Instance.testaction (); Console.WriteLine (Testaction.tojson ()); var test = Callerfactory<itestservice>. Instance.test ("123"); Console.WriteLine (Test. ToJson ());
In this way, the Web API can be consumed in the same way, whether in a Web project, in a WinForm project, or in a cross-platform iOS project (or an Android project), so that all of our data portals are in one place and can focus on the unified development of the business interface. and can effectively manage our data to provide performance issues, such as unified cache processing, unified permissions processing ...
Thank you for the careful reading of this article, I hope that your development has inspired or help.
Use area to classify business in Web API projects