. Net WebApi and. netwebapi

Source: Internet
Author: User

. Net WebApi and. netwebapi

The Service layer is shared with the api layer, indicating that the Service layer is the api layer.

  • Key classes and interfaces

    • System. Web. Http. Dispatcher. DefaultHttpControllerSelector

    Webpai selects the default Implementation of the controller. You can override the SelectController method.

    • System. Web. Http. Controllers. ApiControllerActionSelector

    Webapi selects the default implementation of action under the specified controller. You can override the SelectAction method.

    • System. Web. Http. ApiController

    The base class of the api controller. All classes inherited from this class can become Api controllers.

     

  • Class and interface relationship diagram api custom extension implementation

Api registration process

If the Controller of the Servie layer is implemented.

  • AllServices must inherit from the ApiController class.To enable the Service class to have the Controller feature ApiServier class code (inherit from ApiController, and set the service base class for later extension ):
public class ApiService:System.Web.Http.ApiController{}

TestServer code:

public class TestService:ApiService{    public string Get()    {        return "Get-Test";    }}

Implement Service Classes and have ApiController capabilities

    • Implement the ServiceContainer class, implement service class caching, and use it to select a class for Controller. Obtain the Service Class Code as follows:
private void Init(){    var assembly = System.Reflection.Assembly.GetExecutingAssembly();    var ls = assembly.GetTypes().Where(x => typeof(Services.ApiService).IsAssignableFrom(x));    foreach(var item in ls)    {        _apis.Add(item.FullName, item);    }}
    • Rewrite the api and select the controller class code:
Public class CustomSelectController: System. web. http. dispatcher. defaultHttpControllerSelector {public CustomSelectController (System. web. http. httpConfiguration config): base (config) {} public override HttpControllerDescriptor SelectController (HttpRequestMessage request) {var routeData = request. getRouteData (). values; foreach (var route in routeData) {if (route. key = "controller") {// find the controller Var controllerType = ServicesContainer. createInstance (). apis. where (x => x. key. toLower (). indexOf (route. value. toString () + "service")> 0 ). firstOrDefault (); if (controllerType. value! = Null) {return new DyControllerDescriptor (request. GetConfiguration (), controllerType. Value) ;}} return base. SelectController (request );}}

Note:

public class CustomActionActivator:System.Web.Http.Controllers.ApiControllerActionSelector{    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)    {        if (!(controllerContext.ControllerDescriptor is DyControllerDescriptor))        {            return base.SelectAction(controllerContext);        }        var realType = controllerContext.ControllerDescriptor as DyControllerDescriptor;        Type[] types = new Type[0];        System.Reflection.MethodInfo methodInfo = realType.ControllerInfo.GetMethod("Get",             types);        return new DyActionDescriptor(controllerContext.Configuration, controllerContext.ControllerDescriptor, methodInfo);    }}
  • Note:

     

  • When injecting Api routes to Global. cs, the routes must be injected before Mvc injection.

Protected void Application_Start () {common. servicesContainer. createInstance (); AreaRegistration. registerAllAreas (); // It must be placed in RouteConfig. globalConfiguration. configure (config) => {config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}) ;}); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes); BundleConfig. registerBundles (BundleTable. bundles); GlobalConfiguration. configuration. services. replace (typeof (System. web. http. dispatcher. IHttpControllerSelector), new common. customSelectController (GlobalConfiguration. configuration); GlobalConfiguration. configuration. services. replace (typeof (System. web. http. controllers. IHttpActionSelector), new common. customActionActivator ());}

Running result:

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.