ASP. net mvc whatever you want-KATANA with sharp sharpness, and katana with mvc

Source: Internet
Author: User

ASP. net mvc whatever you want-KATANA with sharp sharpness, and katana with mvc

As described in the previous article, OWIN defines a set of specifications (Specs) between the Web Server and the Web Application, which is intended to decouple the Web Server and Web Application, so as to promote cross-platform implementation. To use the OWIN specification, you must implement it. Currently, two products have implemented OWIN specifications-Katana led by Microsoft and Nowin by a third party. This article focuses on Katana, which is led by the Microsoft team and is open-source to CodePlex. You can enter the command git clone https://git01.codeplex.com/katanaprojectin Visual Studio to compile the source code.
Before introducing Katana, I think it is necessary to sort out the development history of ASP. NET over the past 10 years.
ASP. NET development history ASP. NET Web Form

When ASP. NET Web Form was officially released in 2002, there were two main types of developers:

  • ASP developers who use hybrid HTML tags and Server scripts to develop dynamic websites. In addition, ASP runtime abstracts the underlying HTTP connection and Web Server, it also provides developers with a series of object models for interaction with Http requests, and also provides additional services such as Session, Cache, and State.
  • Programmers who develop WinForm may have no knowledge about HTTP and HTML, but are familiar with Drag Control Methods to build applications.

ASP. NET Web Form uses a heavy ViewState to save the status value during the page return process. Because the HTTP protocol is stateless, ViewState makes the Http protocol that has no memory become remembered. This was a very good design at the time. It was able to quickly develop the Web by dragging controls, without having to focus too much on the underlying principles. The ASP. NET team also enriched ASP. NET with more functions, such as Session, Cache, and Configuration.

This was undoubtedly successful at the time. The release of ASP. NET quickly attracted developers and formed a new force in Web development, but at the same time they also bought some hidden risks:

  • All functions and features are released on an overall framework and tightly coupled with the core Web abstract library-System. Web
  • System. web is. NET Framework, which means to fix and update the System. the Web must be updated. NET Framework,.. NET Framework is the basis of the operating system. It is often not updated frequently for stability.
  • ASP. NET Framework (System. Web) tightly coupled with IIS
  • IIS can only run on Windows
ASP. NET MVC

Because Web Form generates a lot of ViewState and client scripts, this is becoming a burden for developers, because we only want to generate pure HTML tags. Therefore, developers prefer to take the initiative to control rather than passively generate additional HTML tags.

Therefore, Microsoft has launched its important Web Framework, ASP, based on the MVC design model.. net mvc Framework decouples the business logic and performance logic through Model-View-Control. Without server-side controls, the Control of the page is completely handed over to the developer.

For fast update iteration, the update is obtained through Nuget, so it is removed from the. NET Framework.

However, ASP. net mvc is based on ASP. NET Framework (Note: ASP. net mvc 6 does not depend on System. web), so the Web Application and Web Server are still not decoupled.

ASP. NET Web API

With the passage of time, some problems began to be exposed. Due to the tight coupling between Web Server and Web Application, Microsoft became increasingly stretched in the development of an independent and simple Framework, this is in stark contrast to the flourishing development of open-source communities on other platforms. Fortunately, Microsoft has changed and launched an independent Web Framework, ASP. NET Web API, which is applicable to mobile internet and can be quickly installed through Nuget. More importantly, it does not rely on System. web does not depend on IIS. You can deploy Self-Host or other Web servers.

Katana

As Web APIs can run in their own lightweight hosts, more and more simple, modular, and specific frameworks are available, developers sometimes have to start separate processes to process various components (modules) of Web applications, such as static files, dynamic files, Web APIs, and sockets. To avoid process proliferation, all processes must be started, stopped, and managed independently.At this time, we need a public host process to manage these modules.

This is why OWIN was born,Decoupled to components with minimum GranularityThen, these standardized frameworks and components can be easily inserted into the OWIN Pipeline to centrally manage the components. Katana is the implementation of OWIN, providing us with a wide range of Host and Server.

Entering Katana's world

As the OWIN standard implementation, Katana not only implements Host and Server, but also provides a series of APIs to help develop applications, including some functional components such as Authentication) diagnosis, Static Files, ASP. NET Web API and SignalR binding.

Katana's basic principles
  • Portability: the components in each Pipeline are replaceable from Host à Server à Middleware, and the Framework of third-party companies and open-source projects can run on OWIN Server, that is, they are not restricted by the platform, to achieve cross-platform.
  • Modularization: Each component must maintain sufficient independence. Generally, only one task is required to meet the actual development requirements in the form of a hybrid module.
  • Lightweight and efficient: Every component is developed in a modular manner, and you can easily plug and remove components in Pipeline for efficient development.
Katana Architecture

Katana implements the Layers of OWIN, so the architecture of Katana is consistent with that of OWIN, as shown below:

1 .) host: the Host is defined by the OWIN specification at the first layer (bottom layer). Its responsibility is to manage the underlying processes (START and close), initialize the OWIN Pipeline, and select the Server to run.

Katana provides us with three options:

  • IIS/ASP. NET: IIS is the simplest and backward compatible method. In this scenario, OWIN Pipeline is started through the standard HttpModule and HttpHandler. To use this Host, you must use System. Web as the OWIN Server.
  • Custom Host: If you want to replace System with other servers. web, and you can have more control, you can choose to create a custom host, such as using Windows Service, console applications, Winform to host the Server.
  • OwinHost: If you are not satisfied with the two hostnames, the last choice is to use owinhost.exe for katanaworkflow: it is a command line application running at the root of the project, starting the HttpListener Server and finding the constraint-based Startup Item. OwinHost provides command line options to customize its behavior, such as manually specifying the Startup Item or using other servers (if you do not need the default HttpListener Server ).

2.) Server

The Layer after the Host is called the Server. It is responsible for opening the socket and listening to Http requests. Once the request arrives, an Environment Dictionary (Environment Dictionary) that complies with the OWIN specifications is constructed based on the Http request) and send it to the Pipeline for Middleware to process. Katana implements OWIN Server in the following categories:

  • System. web: as described above, System. web and IIS/ASP. NET Host is coupled with each other, when you choose to use System. the Web serves as the Server, Katana System. the Web Server registers itself as HttpModule and HttpServer and processes the requests sent to IIS. Finally, it maps the HttpRequest and HttpResponse objects to the OWIN environment dictionary and sends them to the Pipeline for processing.
  • HttpListener: the default Server of owinhost.exe and custom Host.
  • WebListener: This is the default lightweight Server of ASP. NET vNext. It cannot be used in Katana currently.

3) Middleware

Middleware (Middleware) is located after the Host and Server to process requests in the Pipeline. Middleware can be understood as a component that implements the OWIN application entrusting AppFun.

After the Middleware processes the request, it can be processed by the Middleware component in the next Pipeline, that is, the chain Processing request. The environment dictionary can be used to obtain all Http request data and custom data. Middleware can be a simple Log component or a complex large Web Framework, such as ASP. NET Web API, Nancy, and SignlR, as shown in: Middleware in Pipeline is used to process requests:

4.) Application

The last layer is Application, which is the implementation of specific code, such as ASP. NET Web API and SignalR code.

Now, I think you should have understood what Katana and Katana's basic principles and architecture are, so now it is applied to reality.

Use ASP. NET/IIS to host Katana-based applications
  • Visual Studio creates a Web Application
  • Install-Package Microsoft. Owin. Host. SystemWeb add Startup class
    • ASP. NET/IIS as Host
    • System. Web as Server

The following code implements the OWIN Pipeline processing logic in the Configuration method of Startup:

App. the Run method uses a Lambda expression that accepts the most input parameter of the IOwinContext object and returns the Task as the final processing step of OWIN Pipeline. A strong IOwinContext object is an encapsulation of Environment Dictionary, then output the "Hello World" string asynchronously.

You may have noticed that Microsoft is installed on Nuget. owin. host. the dependency Microsoft. owin assembly, which officially provides us with the extension methods Run and IOwinContext interfaces. Of course, we can also use the original method to output the "Hello World" string, this is the most primitive method provided by the Owin program set. This is only a learning reference, although we will not use it in formal scenarios:

Use custom Host (self-host) to Host Katana-based applications

Using a custom Host to Host Katana applications is not much different from using IIS for hosting. You can use the console, WinForm, and WPF for hosting, but remember, this will lose some features provided by IIS (SSL, Event Log, Diagnostics, Management ...), Of course, this can be implemented by yourself.

  • Create a console application
  • Install-Package Microsoft. Owin. SelfHost
  • Use the Startup configuration item in the Main method to build the Pipeline and listen to the port

Using a custom Host will lose some features of IIS. Of course, we can implement it ourselves. Fortunately, Katana has implemented some features by default, such as Diagnostic, included in the Assembly Microsoft. Owin. Diagnostic.

In the above Code, when the Request Path (Request. Path) is the root directory, rendering the output Webcome PageAnd do not continue executing other Middleware in the PipelineComponents, As shown below:

If the request path is Error, an exception is thrown, and the Error page is displayed, as shown below:

Use owinhost.exe to host Katana-based applications

Of course, we can also use katanaw.owinhost.exe to host applications. There is no doubt that we can use Nuget to install OwinHost.

If you follow the steps in my example, you will find that the Startup configuration class remains unchanged regardless of ASP. NET/IIS hosting or self-hosting. The only change is the hosting method. The same is true for OwinHost, but it is more flexible. We can use a class library or a Web Application as an Application.

  • Use class library

As an Application, the class library can reference the Assembly with minimal effort. After creating a class library, delete the default Class1.cs and add the Startup Item. By default, this will add Owin and Microsoft. reference of the Owin assembly.

Then, use nugetto Install owinhost.exe, such as Install-Package owinhost, which is not a collection, and the. exe application is located in the <solution root>/packages/OwinHost. (version)/tools Folder.

Because the library cannot be directly run, owinhost.exe can only be used for hosting in the kernel root directory. It will load all the assemblies under the. \ binfile, so you need to change the default output of the class library, as shown below:

Then compile the solution, open cmd, and type the following command:

If the Host is successfully started and the default listening port is port 5000.

OwinHost.exe also provides custom parameters, which can be viewed by append-h, as shown below:

Since the class library cannot run directly, you cannot debug it directly. We can attach the OwinHost process for debugging, as shown below:

Note:

I am usingOwinHost.exe 3.0.1If Startup is the following, it prompts that the conversion fails and does not know whether it is a Bug of this version.

The error message is as follows:

  • Use Web Application

Web applications are much easier to use than class libraries. You can run and debug them directly. The only weak one is that they reference a large number of assemblies and you can delete them completely, such as System. Web.

After installing owinhost.exe through nuget, you can use it on the Web, as shown below:

Several Methods for specifying the Startup Item Startup
  • Default name constraint: by default, the Host searches for the Startup class under the root namespace as the Startup Item.
  • OwinStartup Attribute: When the Owin Startup class is created, the Attribute is automatically added, for example:[Assembly:OwinStartup(Typeof(JKXY. KatanaDemo. OwinHost. Startup)]
  • Configuration file, such as: <add key = "owin: appStartup" value = "JKXY. KatanaDemo. Web. StartupDefault"/>
  • If you use a custom Host, you can use WebApp. Start <Startup>("Http: // localhost: 10002") to set the startup Item.
  • If you use OwinHost, you can use the command line parameters as follows:

Advanced Application of Startup Item Startup

The Startup Item Startup supports Friendly Name. With Friendly Name, we can dynamically switch Startup.

For example, during deployment, we have a UAT environment and a Production environment. In different environments, we can dynamically switch Startup to perform different operations.

For example, I created two startups with Friendly Name, as shown below:

  • Production Startup
 1 [assembly: OwinStartup("Production", typeof(JKXY.KatanaDemo.Web.StartupProduction))] 2 namespace JKXY.KatanaDemo.Web 3 { 4     using AppFunc = Func<IDictionary<string, object>, Task>; 5     public class StartupProduction 6     { 7         public void Configuration(IAppBuilder app) 8         { 9            app.Run(context=>context.Response.WriteAsync("Production"));10         }11     }12 }
  • UAT Startup
 1 [assembly: OwinStartup("UAT",typeof(JKXY.KatanaDemo.Web.StartupUAT))] 2  3 namespace JKXY.KatanaDemo.Web 4 { 5     public class StartupUAT 6     { 7         public void Configuration(IAppBuilder app) 8         { 9             app.Run(context=>context.Response.WriteAsync("UAT"));10         }11     }12 }
  • Use the configuration file or OwinHost parameter according to Friendly Name to switch Startup
  <appSettings>    <add key="owin:appStartup" value="Production" />  </appSettings>
Summary

It took a long time to complete this blog and explain the world of Katana. Next I will continue my journey to OWIN & Katana and explore how to create Middleware. Thank you for your support.

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.