ASP. WebAPI Message,httpconfiguration,dependencyresolver

Source: Internet
Author: User
Tags webhost

Message

Webapi as a communication architecture must contain two methods of request and response messages, in Webapi they are httprequestmessage,httpresponsemessage respectively. There are applications in the WEBAPI return results before httpresponsemessage.

Httprequestmessage

Request message contains request address (RequestUri), request method, header information (Headers), message information (Content), and HTTP version (Versions)

    public class httprequestmessage:idisposable    {public        httprequestmessage ();                Public Httprequestmessage (HttpMethod method, String requesturi);                Public Httprequestmessage (HttpMethod method, Uri requesturi);        Public httpcontent Content {get; set;}                Public httprequestheaders Headers {get;}             Public HttpMethod Method {get; set;}               Public idictionary<string, object> Properties {get;}                Public Uri RequestUri {get; set;}                Public version version {get; set;}        public void Dispose ();                protected virtual void Dispose (bool disposing);               public override string ToString ();}

In addition, WEBAPI provides a property of type idictionary<string,object>. We can add any object as an additional property to Httprequestmessage.

Httpresponsemessage

The request message contains the status code (STATUSCODE), the reason (Reasonphrase), the header information (Headers), the message information (Content), and the HTTP version (Versions)

    public class httprequestmessage:idisposable    {public        httprequestmessage ();                Public Httprequestmessage (HttpMethod method, String requesturi);                Public Httprequestmessage (HttpMethod method, Uri requesturi);        Public httpcontent Content {get; set;}                Public httprequestheaders Headers {get;}             Public HttpMethod Method {get; set;}               Public idictionary<string, object> Properties {get;}                Public Uri RequestUri {get; set;}                Public version version {get; set;}        public void Dispose ();                protected virtual void Dispose (bool disposing);               public override string ToString ();}

Httpconfiguration

Httpconfiguration probably has the following functions in Webapi:

    1. Set up a communication pipeline
    2. Store global information (such as Filter,route,formatter)
    3. Provides an IOC architecture for WEBAPI extensions

    public class Httpconfiguration:idisposable {public httpconfiguration ();         Public httpconfiguration (httproutecollection routes);        Public Idependencyresolver Dependencyresolver {get; set;}        Public httpfiltercollection Filters {get;}        Public mediatypeformattercollection formatters {get;}        Public Includeerrordetailpolicy Includeerrordetailpolicy {get; set;}        Public action

For the 1th we have used in every 6 articles. The 2nd will be followed by the following, this article only focus on the 3rd. This feature is primarily done through Servicescontainer, which is the services attribute in Httpconfiguration.

The derived class provided by Webapi to Servicescontainer is Defaultservices, which in Defaultservices contains two methods of dependency injection: 1, single-derived type injection (multi), 2, multi-derived type injection ( Single), that is, the number of derived types that are injected differs. For example, there are querystring,routedata two ways to get the URL parameters, and these two methods are implemented by Querystringvalueprovider and Routedatavalueprovider two types ( The actual defaultservices injection is the factory class for this person's two classes), these two types belong to the parallel relationship, so this time can need to use multi method injection.

These types are injected into the structure of the defaultservces.

    public class Defaultservices:servicescontainer    {        protected defaultservices ();        Public defaultservices (httpconfiguration configuration);         protected override void Clearsingle (Type servicetype);         public override Object GetService (Type servicetype);         protected override list<object> Getserviceinstances (Type servicetype);         public override ienumerable<object> GetServices (Type servicetype);         public override bool Issingleservice (Type servicetype);         protected override void Replacesingle (Type servicetype, Object service);        protected override void Resetcache (Type servicetype);

    Public abstract class Servicescontainer:idisposable {protected Servicescontainer ();         public void Add (Type servicetype, object service);         public void AddRange (Type servicetype, ienumerable<object> services);         public virtual void Clear (Type servicetype);        public virtual void Dispose ();         public int FindIndex (Type servicetype, predicate<object> match);         Public abstract Object GetService (Type servicetype);         Public abstract ienumerable<object> getservices (Type servicetype); public void Insert (Type servicetype, int index, object service);         Vicetype, int index, ienumerable<object> services);         public abstract bool Issingleservice (Type servicetype);         public bool Remove (Type servicetype, object service);         public int RemoveAll (Type servicetype, predicate<object> match);         public void RemoveAt (Type servicetype, int index); public void Replace (Type servicetype, ObjeCT service);     public void Replacerange (Type servicetype, ienumerable<object> services); }

The Servicescontainer only provides a public method of substitution and fetching. Because Servicescontainer only provides standard components in WEBAPI and does not want to act as a public IOC container, these standard components are the basis for WEBAPI expansion.

The following four actions I wrote are get all multiservices, get all singleservices, add a custom valueproviderfactory to Multiservices, Add the custom Iexceptionhandler to singleservices.

        Public Dictionary<type, List<type>> getallmultiservices () {dictionary<type, List            <Type>> result = new Dictionary<type, list<type>> (); FieldInfo field = RequestContext.Configuration.Services.GetType (). GetField ("_defaultservicesmulti", bindingflags.nonpublic|            BindingFlags.Instance); Dictionary<type, list<object>> multiservices = (dictionary<type, list<object>>) field.            GetValue (RequestContext.Configuration.Services);                foreach (var s in multiservices) {list<type> items = new list<type> (); foreach (var item in S.value) {items. ADD (item.                GetType ());            } Result[s.key] = items;        } return result; } public Dictionary<type, Type> getallsingleservices () {dictionary<type, type> Resul t = new Dictionary<typE, type> (); FieldInfo field = RequestContext.Configuration.Services.GetType (). GetField ("_defaultservicessingle", BindingFlags.NonPublic |            BindingFlags.Instance); Dictionary<type, object> services = (Dictionary<type, object>) field.            GetValue (RequestContext.Configuration.Services); foreach (var s in services) {result.            ADD (S.key, S.value==null?null:s.value.gettype ());        } return result; } public Dictionary<type, List<type>> Addmultiservice () {List<valueproviderfactor            Y> valueproviderfactories=new list<valueproviderfactory> () {new Querystringvalueproviderfactory (),            New Routedatavalueproviderfactory (), New Myvalueproviderfactory ()};            RequestContext.Configuration.Services.ReplaceRange (typeof (Valueproviderfactory), valueproviderfactories); Return getalLmultiservices (); } public Dictionary<type, Type> Replacesingleservice () {RequestContext.Configuration.Servi Ces.            Replace (typeof (Iexceptionhandler), New Myexceptionhandler ());        return getallsingleservices (); }

Because the type injection in Servicescontainer is fixed, WEBAPI extends a set of methods for getting the service to Servicescontainer

    public static class Servicesextensions {public static Ihttpactioninvoker Getactioninvoker (This Servicescont         Ainer services);         public static Ihttpactionselector Getactionselector (this servicescontainer services);         public static Iactionvaluebinder Getactionvaluebinder (this servicescontainer services);         public static Iapiexplorer Getapiexplorer (this servicescontainer services);         public static Iassembliesresolver Getassembliesresolver (this servicescontainer services);         public static Ibodymodelvalidator Getbodymodelvalidator (this servicescontainer services);         public static Icontentnegotiator Getcontentnegotiator (this servicescontainer services);         public static Idocumentationprovider Getdocumentationprovider (this servicescontainer services);         public static Iexceptionhandler Getexceptionhandler (this servicescontainer services); public static ienumerable<iexceptionlogger> Getexceptionloggers (This ServicescontaiNER services); public static ienumerable<system.web.http.filters.ifilterprovider> Getfilterproviders (This ServicesContainer         Services);         public static Ihostbufferpolicyselector Gethostbufferpolicyselector (this servicescontainer services);         public static Ihttpcontrolleractivator Gethttpcontrolleractivator (this servicescontainer services);         public static Ihttpcontrollerselector Gethttpcontrollerselector (this servicescontainer services);         public static Ihttpcontrollertyperesolver Gethttpcontrollertyperesolver (this servicescontainer services); public static ienumerable<system.web.http.modelbinding.modelbinderprovider> Getmodelbinderproviders (this         Servicescontainer services);         public static Modelmetadataprovider Getmodelmetadataprovider (this servicescontainer services); public static ienumerable<modelvalidatorprovider> Getmodelvalidatorproviders (this servicescontainer services)         ; public static Itracemanager GEttracemanager (this servicescontainer services);         public static Itracewriter Gettracewriter (this servicescontainer services); public static ienumerable<system.web.http.valueproviders.valueproviderfactory> Getvalueproviderfactories (    this servicescontainer services); }

There is a globalconfiguration in ASP. Webapi, but it's not part of WEBAPI. Webapi is just a stand-alone framework. It needs to be hosted under another application to run. The homestay model is divided into two types of webhost,selfhost,webhost that are hosted on Web programs. Because this series only discusses the Webapi under ASP., so just talk about the webhost mode.

Assembly System.Web.Http.WebHost is referenced in ASP. Webapi. Globalconfiguration is under the assembly. It contains a Httpconfiguration property. Also a way to configure Httpconfiguration

There's another httserver.

In addition, many properties of Apicontroller can be found Httpconfiguraiton
Configuration

Controllercontext.configuration

Requestcontext.configuration

These httpconfiguration are derived from references to globalconfiguration.configuration.

Dependencyresolver

WEBAPI provides us with an IOC framework, the Dependencyresolver

Public interface Idependencyresolver:idependencyscope, IDisposable {idependencyscope beginscope ();  Interface Idependencyscope:idisposable {Object GetService (Type servicetype); Ienumerable<object> getservices (Type servicetype);  

Idependencyresolver also inherits the Idependencyscope, so we can see idependencyscope as a dependency context.

Dependencyresolver in Webapi is not registered in Servicescontainer like other components, but is registered directly in httpconfiguration (Dependencyresolver attribute).

A httprequestmessage. There is also an extension method getdependencyscope to get Dependencyscope, This method obtains the dependencyresolver of the properties of Httprequestmessage, where Dependencyresolver is also from Httpconfiguration.

In the WEBAPI also defines a emptyresolver, it is only an empty resolver, so in the WEBAPI default is the use of direct reflection mode.

ASP. WebAPI Message,httpconfiguration,dependencyresolver

Related Article

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.