Introduction to ASP. NET +MVC of ASP.

Source: Internet
Author: User

1. What is MVC?

Before introducing MVC, say a autonomous view: combine the rendering of the UI interface, the capture response of interactive actions, the logical processing flow, the data store, and so on (e.g. WebForm), we make this design pattern an autonomous view

The drawbacks of the Autonomous view:

    • A combination of views and logic that is not conducive to logical reuse
    • Not conducive to debugging a UI component

MVC is an architectural model based on the principle of separation of concerns, which divides the functions of a human-computer interaction user into model, View, controller three parts, each of which has its own responsibilities:

Model: is a package for state and business functions, a domain model that includes both behavior and data, and the model receives the controller's request to complete the appropriate business processing to notify the view when the state changes

View: Visualize the rendering of the interface while capturing the user's interactive actions

controller: Receives the interactive operation of the view capture, completes the corresponding UI logic, and if the requirements involve the requirements of the business logic, then the controller calls the model directly, and after the UI logic processing is completed, The controller will control the existing view or create a new view to respond to user requests.

The interaction between Model-view-controller

Controller is not only between the model and the view of the intermediary between model and view can also be directly interactive, when the model state changes, it can directly notify the View,view can also actively query the model state information.

What is the relationship between MVC and the "three-tier structure"?

There is no comparability between the two, and for multi-tiered architecture patterns, MVC is often used as a design pattern for the UI layer (ASP. NET MVC is often considered to be the UI layer of MVC), and the model is more of a gateway to the business Access layer.

2. IIS and ASP. 2.1 IIS 5.x and ASP.

IIS 5.x runs in the InetInfo.exe process, which hosts a Windows service called W3SVC (World Wide Web Publishing Serivice) that includes the ability to listen for HTTP requests, Worker processes and configuration management (through metadata (Metadata) for related configuration information)

When an HTTP request is received, determine whether the requested static resource is based on the suffix name, and if so, the requested resource is returned directly in HTTP, and if it is a dynamic resource, the appropriate ISAPI dynamic-link library (DLL) is located from the script map of IIS based on the extension.

ISAPI (Internet Server application programing Interface) is a set of local win + APIs that are a link between Web applications and IIS, and the corresponding DLL for the ASP. NET ISAPI is aspnet_ Isapi.dll (located in Sysdir:\windows\microsoft.net\framework\versioninfo), ISAPI supports ISAPI (ISAPI Extension) extensions and ISAPI filtering (ISAPI Filter), which is the interface that really handles HTTP requests, which is validating, forwarding, or rejecting requests before processing the request.

If an ASP. NET-type-based resource is requested, the ASP. NET ISAPI is loaded, Aspnet_isapi A worker process that creates an ASP (if the process has not yet started), for iis5.x the process is asp.net.exe, during the initialization of the worker process, the main thread of the worker process initializes the CLR,

For a Web request, the CLR creates an application domain, the HTTP runtime (isapiruntime) in the application domain is loaded and the appropriate app is created, and in iis5.x all Web apps exist in the same worker process (aspnet_ Wp.exe) in a different application domain.

2.2 IIS 6.x and ASP.

IIS 5 flaw in processing HTTP requests:

    1. The ASP. NET ISAPI Dynamic link library is loaded directly into the InetInfo.exe process, which is based on communication between processes and is prone to performance bottlenecks
    2. All Web applications run in different application domains of the same worker process, and application-domain-based isolation does not fundamentally address the impact between different applications

To solve the first problem, iis6.x loads the ASPNET_ISAPI dynamic link library directly into the worker process, and for the second issue, IIS 6 creates the application pool mechanism, and we can create an application pool for one or more web apps, one for each application pool, Provides process-based isolation for web apps.

Note: the HTTP. sys in the figure is a kernel driver that listens for an HTTPS request, and when the HTTP. Sys is heard by a request, it is distributed to w3svc, W3SVC resolves the requested URL. The requested Web application is defined according to the URL in metadata with the Web app, and the worker process that the target application runs is further obtained, and if it has not yet been created, a worker process is created for that request (called a request-creation), during the initialization of the worker process aspnet_ ISAPI dynamic link library is loaded ..... , the ASP. NET ISAPI then loads the CLR, creates the application domain, initializes the application.

2.3 IIS 7 and ASP.

IIS 7 has revolutionized the listening and distribution mechanisms of requests, mainly in the introduction of Windows Process Activation service was (Windows Processes Activation service), Some of the functions hosted by the W3SVC service in IIS6 have been diverted to Was,w3svc, which has three main parts:

    1. HTTP request receive: HTTP request received by
    2. Configuration management: Load configuration information from metadata configuration related components
    3. Process Management: Process creation, recycling, monitoring processes

IIS 7 assigns the latter two functions to was, and the receipt of the HTTP request is still introduced by W3svc,was to support the non-HTTP protocol for IIS 7, which abstracts different protocol listeners through the Listener adapter interface (ASP. NET MVC 4 Framework decryption P17)

Either the HTTP request received from the W3SVC, or the request received from the WCF listener adapter, is eventually committed to was and is created if the corresponding worker process has not been established, otherwise the request is distributed to other processes for subsequent processing, and was in the request process, The configuration information is loaded with the corresponding configuration management module, and the related components are configured, unlike IIS5 and IIS 6, the configuration information of IIS7 is not saved in the metadata, but in the configuration file in XML format, the basic configuration is in applicationhost.config.

3. ASP.

HTTP. SYS receives an HTTP request, if the request is the first request to the Web app, Aspnet_isapi load CLR,CLR creates an application domain for the Web app through Appdomainfactory. After a runtime called Isapiruntime is loaded and the loaded Isapihttpruntime receives the request, Isapihttpruntime first creates a isapiworkerrequest (subclass of the Httpworker class, All HTTP requests must be encapsulated into a HttpWorkerRequest object for subsequent processing, and the object is passed to the runtime httpruntime of ASP. HTTP requests go to the ASP. HttpRuntime creates a HttpContext object for the current request context object based on the Isapiworkerrequest object

When the HttpContext object is created successfully, HttpRuntime uses HttpApplicationFactory to create a new or get a HttpApplication object. HttpApplicationFactory internally maintains a pool of HttpApplication objects, httpruntime selects HttpApplication objects from the pool to handle HTTP requests. Dispose of objects in the object pool after processing is complete (each HttpApplication can only process one request)

During the initialization of the HttpApplication object, the registered HttpModule object is loaded and initialized according to the configuration file, and for HttpApplication, different events are triggered at different stages of the processing of the HTTP request. The HttpModule is to inject the operation of these events into the process of request processing (by registering the corresponding HttpApplication event), HttpApplication has 19 pipeline events, as follows:

Many of the features of ASP, such as authentication, caching, and authorization, are implemented through HttpModule

register for HttpModule and HttpApplication events:http://www.cnblogs.com/kissdodog/p/3527922.html

The real HTTP request processing is made by HttpHandler. For different resources have different httphandl (but all implemented IHttpHandler this interface, IHttpHandler ProcessRequest method request processing specific implementation), such as the web The HttpHandler for the form corresponds to system.web.pageui,asp.net mvc HttpHandler for Mvchandler.

HttpApplication is the core of the entire Web application processing, when the first request is received, ASP. NET creates multiple HttpApplication objects, puts them into the pool, chooses one to process the current request, and does not recycle directly after processing is completed. Instead, it is released into the HttpApplication object pool for subsequent requests, and if all HttpApplication objects in the pool are busy, a new HttpApplication object is created.

There are two ways to register HttpHandler for HttpApplication pipeline events, one through the Web. config configuration file, and the other through the Global.asmx file.

Method One:

    1. First define a class implementation IHttpModule interface, the IHttpModule interface is defined as follows:

The child element of the system.web configuration element httpmodules is used to configure the child elements of the httpmodule;httpmodules used by the Web site add to add a new httpmodule;clear will clear all previously registered HttpModule.

The add element has two required properties name and type, as described below:

    • Name indicates the name of the HttpModule in the program, which can be used to find a reference to the HttpModule object in the Web application. The Modules property of HttpApplication represents all HttpModule objects associated with this object, and the corresponding HttpModule object can be found by using this name as the indexer.
    • Type represents the name of the HttpModule object, and the ASP. NET Web site can use this type name to dynamically create HttpModule objects through reflection. A type is written as a type name that is required in reflection, and if the class is defined in a Web site, then it is the full name of the class that contains the namespace, otherwise, after the full name, separated by commas (,), and with the name of the assembly where the type resides, the name of the assembly does not need to include the. dll extension

Method Two: Through the Global.asmx file to achieve

in Global.asax, event handling for HttpApplication can be accomplished by defining a special naming method. First, these methods must conform to System.EventHandler because all HttpApplication pipeline events Use this delegate definition. Second, the scope of the method must be public. Thirdly, the naming format of the method must be as follows: Application_ registered event name. The methods defined in Global.asax by this naming method will be automatically registered to the corresponding event.

For example, to register Postauthenticaterequest event handling in Global.asax, you should define a method such as the following in Global.asax:

4. ASP. NET MVC Overall processing Process 4.1 URL parsing

For an ASP. NET Mvcweb application, the request processing of HTTP is implemented by the corresponding action method of the controller, so the first task of ASP is to parse the corresponding controller and action from the request URL. The parsing of URLs in ASP. NET MVC is done by UrlRoutingModule. UrlRoutingModule implements the IHttpModule interface, in its init () method, registers the 7th event of a HttpApplication pipeline event Postresolverequtestcache

The following is the main processing code for Postresolverequestcache:

Several things were done during this period:

    1. Encapsulates the current request information HttpContext object further encapsulated as a httpcontextwraper (subclass of HttpContextBase) object and passed it as a parameter into the Postresolverequestcache method
    2. Call RouteCollection (internally with a dictionary collection that holds the currently registered routing information), and if the match succeeds, returns a Routedata object that encapsulates the matching route object, otherwise, It returns NULL,
    3. Further encapsulate the acquired Routedata and HttpContext as RequestContext objects
    4. Gets an object of type Iroutehandler (Mvcroutehander) by calling Routedatad's Getroutehandler property as a parameter of the RequestContext object that was encapsulated in the previous step
    5. Call Iroutehandler's Gethttphander method to return an object of type Ihttphander (Mvchandler)
Activation of the 4.2 controller

urlroutingmodule resolves the current HTTP request through the routing table and obtains a routedata to encapsulate the routing data. Then call Routehandler's Gethttphandler method to get the HttpHandler object and register it in the HTTP context, because Routedata Routehandler from Route Routehander, It is a mvcroutehander by default, so this is the mvchandler that is used by default for processing MVC requests (you can see the Maproute method of routecollectionextension to confirm), The activation and execution of the Controller object is done in Mvchandler.

Mvchandler implements the IHttpHandler interface and implements the controller activation and execution in its ProcessRequest method.

The code in the PR method is as follows:

The implementation of the main function is in the encapsulated inner function processrequestinit (), the method is as follows

Here are a few things that have been done:

    1. Gets the HTTP context of the current request from the parameter (a httpcontextwraper is passed in the parameter)
    2. Get the controller name from RequestContext (encapsulated Routedata and HttpContext)
    3. Gets the factory object that created the controller through Controllerbuilder (used to set or get the Controller object Factory) object (default is the Defaultcontrollerfactory object)
    4. Call the Createcontroller method of the factory object to create a controller object (by reflection) based on the RequestContext and controller name

Execution of the 4.3 action

The action is executed in the controller's Excute (RequestContext context) Method (The Excute () method of the controller is executed in the ProcessRequest () method of the Mvchandler (see PR method)), Its core lies in the execution of the action method and the execution of the ActionResult returned as a method.

Note: Both the Controllerbase and controller implement the IController interface, and the controller inherits from Controllerbase, which explicitly implements the interface in Controllerbase IController

An instance method Excute (RequestContext RequestContext) called with the same name in the Excute method of IController.

As you can see, the main operation of the instance method Excute has the Excutecore () method called the Controllerbase, and the method is a virtual method, so any class that inherits Controllerbase must override the method. In the Controller method is not explicitly implemented IController Excute (may be ambiguous, here refers to the controller inherited Controllerbase Excute method, and did not implement), Instead, rewrite the Excutecore method, overriding the Excute method as follows:

First call the Getactionname method to get the action name of the request, then call Actioniinvoker's Invokeaction method, this method mainly does the following several things:

    1. Execute Action Filter method
    2. Executing the Action method
    3. Executes the ActionResult returned as a method

If this actionresult is Viewresult, call the corresponding view engine to render the view

The above is an overall request processing process for ASP.

Introduction to ASP. NET +MVC of ASP.

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.