Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Viewing the Adapter pattern from the HttpMessageHandlerAdapter of System.Web.Http.Owin

2025-03-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

one。 Write at the front

Adapter pattern (Adapter)

Can be used to adapt between existing interfaces and incompatible classes. It helps avoid large-scale rewriting of existing customer code, which works by wrapping the interface of an existing class so that clients can use a class that is not tailor-made without major surgery. -"JS Design pattern"

Convert the interface of one class into another interface expected by the customer. Adapters allow classes with incompatible interfaces to work together.

-"Head First Design pattern"

This is the definition of adapter patterns in these two books. Adapter patterns are relatively easy to understand among a variety of design patterns. The purpose or problem that can be solved is new functions / new types. It is not compatible with the original type / method / function. With the ingenious experience of adapters, we can ensure that they are closed to modification and open to expansion. To achieve this, it is necessary to face the interface and maintain the oneness of responsibility. Perhaps the most common sight for C # developers is SqlDataAdapter.

two。 Get to know UseWebApi

The OWIN,.NetFramework,Webapi open source xxx addresses involved in this article are:

Ht t p s: / / g i t h u b. C o m / as p n et / A s p N et K a ta n a

Htt p s: / / g i th u b. C o m / AS P-N E T-M V C / a s p n e tw e b s t a ck

H t t p s: / / g i t h u b. C om / d o t ne t / c or e f x

Friends who are familiar with the OWIN system must have seen and used app.UseWebApi in Startup.cs. App is the object of IAppBuilder

Startup.cs is the startup class of OWIN katana implementation. Just as the name implies, UseWebApi is to put WebApi as an OWIN middleware in the whole processing flow. App is the object of IAppBuilder, and IAppBuilderFactory is responsible for its creation. IAppBuilder defines three methods, which are Build,New and Use. What are these three methods responsible for respectively?

Build, which returns an instance of the entry point of the OWIN pipe, which is called by the Init method in Microsoft.Owin.Host.SystemWeb. The returned instance will be converted to the AppFun type. What is AppFun (using AppFunc = Func;)? It is an application delegate for the OWIN server to interact with the application, and we should be able to guess why when we see this method called in OWIN.Host.

New, which is used to return an instance of AppBuilder, which is called and returned by IAppBuilderFactory.

Use is the method that we often use in OWIN system, we can define our own OWIN middleware, according to its definition specification, and Use to the processing pipeline, such as user operation log middleware, user identification middleware and so on.

At this point, we should clearly understand that WebApi is just a middleware of OWIN. Take a chestnut:

1 public partial class Startup 2 {3 4 public void Configuration (IAppBuilder app) 5 {6 / / This must happen FIRST otherwise CORS will not work. 7 / introducing OWin.Cors to solve cross-domain access problems 8 app.UseCors (CorsOptions.AllowAll); 9 10 GlobalConfiguration.Configure (WebApiConfig.Register); 11 FilterConfig.RegisterGlobalFilters (GlobalFilters.Filters); 12 13 ConfigureAuth (app); 14 15 app.Use (); 16 app.Use () 17 app.UseWebApi (GlobalConfiguration.Configuration); 18} 19}

III. Implementation of UseWebApi

When you see here, you must ask why there is no UseWebapi method defined in IAppBuilder. The implementation of UseWebapi in System.Web.Http.Owin 's WebApiAppBuilderExtensions.cs, UseWebApi is a C # this extension method, which is no different from the answer you have in mind. In its implementation, builder.Use (typeof (HttpMessageHandlerAdapter), options) is called.

At this point, be sure to say a few words and don't blame me, the implementation steps of Adapter: in order to make a class or a function compatible with existing classes / interfaces, then

1. The interface or abstract method of the target customer is implemented by the adapter to facilitate the passing of parameters

two。 The method of the target customer is called in the method of the implemented interface / abstract class

The protagonist HttpMessageHandlerAdapter has finally appeared, and friends who understand the Adapter pattern must be able to imagine that since it is the Adapter of HttpMessageHandler, there must be a field of private defined in its class, and the type is HttpMessageHandler. You can also imagine that this Adapter inherits the abstract type OwinMiddleware and implements its Invoke abstract method, and the HttpMessageHandler method must be called in a method of HttpMessageHandlerAdapter. So through the source code, we know that the field of HttpMessageHandler is named _ messageHandler. (is it similar to the Adapter implementation mentioned above, which may not be summarized well? please refer to more articles and examples.)

Asp.Net Webapi's message processing pipeline is a processing pipeline composed of HttpMessageHandler's delegate chain.

The top one of the HttpMessageHandler abstract classes is a unique abstract method for implementation, whose input parameter is HttpRequestMessage and its output parameter is HttpResponseMessage.

1 protected internal abstract Task SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)

DelegatingHandler implements HttpMessageHandler with HttpMessageHandler passed into its constructor and a delegate chain formed by a similar object innerHandler.

Recommend a MS document https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers, can refer to slightly if you are interested.

1 protected DelegatingHandler (HttpMessageHandler innerHandler) 2 {3 InnerHandler = innerHandler; 4} 5 6 protected internal override Task SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) 7 {8 if (request = = null) 9 {10 throw new ArgumentNullException (nameof (request), SR.net_http_handler_norequest); 11} 12 SetOperationStarted () 13 return _ innerHandler.SendAsync (request, cancellationToken); 14}

There is a long string in the middle, in order to illustrate the role of HttpMessageHandler, so that we can further understand why there is HttpMessageHandlerAdapter and introduce this type in the case of Use (WebApi middleware).

In the HttpMessageHandlerAdapter constructor, _ messageHandler is wrapped as a HttpMessageInvoker type, which is designed to provide a special class for calling SendAsync methods.

We have just learned that HttpMessageHandlerAdapter implements OWinMiddleware, so we know from the source code what it does in its abstract method Invoke: it calls the InvokeCore method under the same class, Create the HttpRequestMessage in InvokeCore, and takes its object as the input parameter of SendAsync, and finally gets the HttpResponseMessage object.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report