Next Generation ASP Owin (3)--middleware

Source: Internet
Author: User

Middleware is the basic constituent unit of the Owin pipeline, finally stitching the Owin pipeline to process the client request and output the Web page. In this article, first look at web Form, MVC, how the Web API is used in conjunction with Owin. Then how to write middleware and write a specific cache middleware.

Read the catalogue:

I. How does an MVC project integrate Owin with the original web Form?

1.1 Through routing configuration, the program is divided into sections, some of which are processed by ASP. NET Web form or MVC, and the other part is handled by the Owin pipeline.
1.2 Insert Owin before web Form, MVC

Two. Web API registered with middleware to Owin pipeline

Three. Customizing the cache middleware

3.1 HelloWorld Middleware
3.2 Cache Middleware

Four, summary

One, the original web Form, MVC Project How to combine Owin?

Bad news, I'm sorry, although Owin is revolutionary, Web form and MVC are not yet integrated into the Owin pipeline as a middleware . The reason for this is that the Web Form and MVC rely on many types in System.Web.dll in the first article, which is analyzed in the history of ASP . In the Owin pipeline, these dependencies are not available. The good news, however, is that in ASP. NET vNext , it will be a complete farewell to System.Web.dll dependencies, at which time, the ASP. NET VNext will be the synthesizer. I heard that the VNext project team is working with the Mono team to enable the project that ASP . NET VNext develop to run on the *nix, OSX system.

So in the current case,owin and Web form, the combination of MVC development is generally two forms:

1. Through the routing configuration, the program is divided into sections, some of which are processed by ASP. NET Web form or MVC, and the other part is handled by the Owin pipeline.

//How to hooks OWIN pipelines into the normal ASP. NET route table side by side.protected voidApplication_Start (Objectsender, EventArgs e) {     //Owin Opening access path will be sent to Startup.cs initialized Owin pipeline processingRouteTable.Routes.MapOwinPath ("/owin"); //The access path at the beginning of the special will be handled by the OWINAPP2 pipelineRouteTable.Routes.MapOwinPath ("/special", app ={app.     Run (Owinapp2.invoke); });}

As the code above, in the Application_Start function or the routing configuration function, different Owin pipelines are configured for the/owin path and/special respectively.
The complete code, please go here http://aspnet.codeplex.com/sourcecontrol/latest#Samples/Katana/AspNetRoutes/Global.asax.cs

2. Insert Owin before web Form, MVC

In Web Form and MVC projects, you can also add Startup.cs, specifying the type of initialization that becomes owin, then the request is processed by the Owin pipeline and finally to the Web Form or MVC program. This approach is often used to configure log, authentication, cache, and so on middleware.

Second, the Web API is registered with middleware to the Owin pipeline

Web APIs are not dependent on System.web.dll, so the Web API can be registered as middleware in the Owin pipeline .

Here's how:

   Public classStartup {//invoked once at the startup to configure your application.         Public voidConfiguration (Iappbuilder builder) {httpconfiguration config=Newhttpconfiguration (); Config. Routes.maphttproute ("Default","Api/{controller}/{customerid}",New{controller ="Customer", CustomerID = routeparameter.optional});//define the Web API Route//XML format output resultsConfig. Formatters.XmlFormatter.UseXmlSerializer =true; Config. Formatters.remove (config.            Formatters.jsonformatter); //CONFIG.            Formatters.JsonFormatter.UseDataContractJsonSerializer = true; //registering the Web API with middleware in the Owin pipelineBuilder.        Usewebapi (config); }    }
Three, custom cache Middleware3.1 HelloWorld Middleware

First build a middleware by inheriting the Owinmiddleware base class. The function of this middleware is very simple, which is to print the current system time.

 public  class   helloworldmiddleware:owinmiddleware{ public< /span> Helloworldmiddleware (Owinmiddleware next): base   (next) {}  public  override Task Invoke (Iowincontext context) { var  response = "  hello world!           It is   + DateTime.Now; Context.           Response.Write (Response);        return   Next.invoke (context); }}

After registering the middleware with the Owin pipeline, the resulting web page is executed:

As long as we constantly refresh the page, each display will be different, because each time the system time is re-read, re-render the page.

3.2 Cache Middleware

The idea of implementing the cache middleware is simple, to access the URL as key, to output the content as value. During the first visit, the output will be cached and the content will be returned to the cache at the next visit, rather than regenerated. The specific code is as follows:

 Public classCachemiddleware:owinmiddleware {Private ReadOnlyidictionary<string, cacheitem> _responsecache =Newdictionary<string, cacheitem> ();//Dictionary of Cache storage        PublicCachemiddleware (Owinmiddleware next):Base(next) {} Public OverrideTask Invoke (Iowincontext context) {context. environment["Caching.addtocache"] =NewAction<iowincontext,string, timespan>(Addtocache); varPath =context.           Request.Path.Value; //if the path accessed is not cached, it is passed to the next layer of the Owin pipeline for processing           if(!_responsecache.containskey (path)) {               returnNext.invoke (context); }           varCacheItem =_responsecache[path]; //Check if the cache expires           if(Cacheitem.expirytime <=DateTime.Now) {_responsecache.remove (path); returnNext.invoke (context); }           //output directly from the cache instead of re-render the pagecontext.           Response.Write (Cacheitem.response); returnTask.fromresult (0); }       //The method of adding the cache will be stored as a delegate to the Owin pipe dictionary so that any Owin middleware can be called to save the data to the cache        Public voidAddtocache (Iowincontext context,stringresponse, TimeSpan cacheduration) {_responsecache[context. Request.Path.Value]=NewCacheItem {Response = Response, Expirytime = DateTime.Now +CacheDuration}; }       Private classCacheItem { Public stringResponse {Get;Set; }//Save the cached content            PublicDateTime Expirytime {Get;Set; }//determining the time of the cache       }   }
View Code

Next, we'll transform the Helloworldmiddleware, and after the helloworldmiddleware output, we'll save the output to the cache. The specific code is as follows:

 Public classHelloworldmiddleware:owinmiddleware { PublicHelloworldmiddleware (Owinmiddleware Next):Base(next) {} Public OverrideTask Invoke (Iowincontext context) {varResponse ="Hello world! It is"+DateTime.Now; if(Context. Environment.containskey ("Caching.addtocache"))//here, directly from the dictionary of the Owin pipeline, check for the add cache and, if present, cache the output to the cache with an expiration time of 10 minutes.            {               varAddtocache = (Action<iowincontext,string, timespan>) context. environment["Caching.addtocache"]; Addtocache (context, Response, Timespan.fromminutes (Ten)); } context.           Response.Write (Response); returnTask.fromresult (0); }   }
View Code

Finally, add cachemiddleware to the Owin pipeline to play a role, note the order of the registration pipeline problem, middleware is to be sure before helloworldmiddleware.

 Public class startup{    publicvoid  Configuration (Iappbuilder app)    {        app. use <CacheMiddleware>();        App. use <HelloWorldMiddleware>();    
Four, summary

In the example above, I hope we have some basic concepts on how to write middleware.
Owin Advantage in the above example should be some embodiment, is middleware through data and code of conduct, we can work together seamlessly, any third-party middleware can be very simple integration into the Owin pipeline, this should be the greatest charm of Owin, Open to charm.
at the same time, Owin's goal is to unify web Form, MVC, and Web APIs into a single large platform, which will be more helpful for mixed programming.

Next Generation ASP Owin (3)--middleware

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.