Asp. NET's operation principle and operation mechanism

Source: Internet
Author: User

In Asp.net4 and 4.5, the webpages Framework was added, writing page code using the new razor syntax, the code is more concise and conforms to the web standards, and is written in a way closer to PHP and previous ASP, And the use of WebForms this imitation of Windows Form programming is very different, there is no large number of controls and controls generated by a large number of inflexible code, but also can use the large number of ASP. NET provides the class library and features, can say that the webpages framework fused ASP, The full benefits of PHP and ASP, and the use of C # and VB programming languages. At the sight of the webpages framework, I immediately had an interest in deep learning, as it would immediately give the webforms of a perfectionist complex a crush.

But the webpages framework does not have a binding razor syntax, and it can use a third-party view engine. Webpages and razor are not necessarily associated with ASP. In VS2012, the default Web site template is more than "ASP. Razor v2", you can create webpage from Razor syntax.

Webpages website profile

Webpages Web site contains multiple cshtml or vbhtml pages, these pages use razor template syntax, the entire Web site files are in a folder, the Bin directory has a variety of DLLs to use, no solution files, The solution file is in another project created concurrently with the Web site, which has the packages directory to manage the packages that are needed for the webpages site. A common cshtml page code is as follows:

@{     var db = ("Startersite");     var users = db. Query ("SELECT * from UserProfile");     var Grid = new WebGrid (users); } <! DOCTYPE html>

As you can see, this kind of writing is similar to PHP, ASP, but behind the webpages is a huge net-like library.

Webpages framework-related configuration

There is no special configuration in Web. config in the webpages Web site, and the related configuration in Web. config in. NET Framework 4.0 is as follows:

<compilation>    <assemblies>        <remove assembly= "System.Web.WebPages.Deployment, version=, culture=neutral, publickeytoken=31bf3856ad364e35 "/>        <add assembly=" System.Web.WebPages.Deployment, version=, culture=neutral, publickeytoken=31bf3856ad364e35 "/>    < Add assembly= "System.Web.WebPages.Deployment, version=, culture=neutral, publickeytoken=31bf3856ad364e35"/ >     </assemblies></compilation>

There is no configuration of the relevant buildproviders and no related httpmodules configuration, and HttpHandlers's configuration also maps it to HttpForbiddenHandler forbidden access. The configuration in IIS or IIS Express also has only the asp.net4.0 ISAPI configuration and no associated HttpModule. The WebForms is configured with the corresponding HttpHandler and buildprovider in Web. config. So how does the webpages framework work, and where does the webforms differ, and how the webpages framework is implemented under the ASP, which needs to go into the webpages framework for exploration.

Webpages Framework Auto-run process

Starting with the System.Web.WebPages.Deployment assembly in Web. config, this assembly DLL has a asp.net4.0 new feature Preapplicationstartmethodattribute, which configures a static method to be executed automatically before the program starts, with the following features: [Assembly:preapplicationstartmethod (typeof (Preapplicationstartcode), "Start")], Look at the start method of the Preapplicationstartcode class, which calls the Startcore method, and Startcore calls the Loadwebpages method, The main function is to get all the DLLs related to webpages framework and get the starting method corresponding to the Preapplicationstartmethodattribute features configured on these DLLs and execute them all. DLLs with this feature are System.Web.WebPages, System.Web.WebPages.Razor, and Webmatrix.webdata, and we focus on the top two.

private static void Loadwebpages (version version)

New Func<assemblyname, assembly> (null, (INTPTR) loadassembly));

foreach (Assembly Assembly in assemblies)
buildmanager.addreferencedassembly (assembly);
foreach (MethodInfo info in getprestartinitmethodsfromassemblycollection (assemblies))

Info. Invoke (null, NULL);

The startup method code on the System.Web.WebPages.Razor assembly is as follows:

public static class Preapplicationstartcode {     //fields    private static bool _startwascalled;      Methods public    static void Start ()     {         if (!_startwascalled)         {            _startwascalled = true;             Buildprovider.registerbuildprovider (". cshtml", typeof (Razorbuildprovider));             Buildprovider.registerbuildprovider (". vbhtml", typeof (Razorbuildprovider));         }    } }

It registers the cshtml and vbhtml files corresponding to the BuildProvider for Razorbuildprovider, which is the provider that compiles the razor grammar file.

The startup method code on the System.Web.WebPages assembly is as follows, the names and methods of these startup classes are the same

public static class Preapplicationstartcode {     //fields    private static bool _startwascalled;      Methods public    static void Start ()     {        if (!_startwascalled)         {             _startwascalled = true;             Webpagehttphandler.registerextension ("cshtml");             Webpagehttphandler.registerextension ("vbhtml");             Pageparser.enablelongstringsasresources = false;  This line of code registered Webpagehttpmodule            dynamicmoduleutility.registermodule (typeof (Webpagehttpmodule));             Scopestorage.currentprovider = new Aspnetrequestscopestorageprovider ();         }     } }

One of the most important features is the automatic registration of a httpmodule, so we can know that the Webpages page compilation and processing has been landed. Then look at the code for Webpagehttpmodule, which HttpModule registered to handle the Postresolverequestcache,beginrequest and endrequest events of HttpApplication. This code triggers execution when the user requests cshtml and vbhtml pages. In this process webpagehttpmodule will also call the System.Web.WebPages.ApplicationStartPage.ExecuteStartPage method when the webpages site is first launched, in postresolverequ The Estcache event handler code calls the Webpageroute method, which creates the Webpagehttphandler class that handles the page.

internal static void Onapplicationpostresolverequestcache (object sender, EventArgs e) {httpcontextbase context = new H Ttpcontextwrapper (((HttpApplication) sender).  Context);     New Webpageroute (). Dopostresolverequestcache (context); }
internal void Dopostresolverequestcache (HttpContextBase context) {if (!this. isexplicitlydisabled) {String pathvalue = context. Request.AppRelativeCurrentExecutionFilePath.Substring (2) + context.         Request.pathinfo;         readonlycollection<string> registeredextensions = Webpagehttphandler.getregisteredextensions (); Webpagematch match = Matchrequest (Pathvalue, registeredextensions, this.         Virtualpathfactory, context, displaymodeprovider.instance); if (match! = null) {context.             Items[typeof (webpagematch)] = match; String path = "~/" + match.        Matchedpath; is the webpages:enabled if (!) explicitly configured in the Web. config of the webpages website. webpagesdeployment.isexplicitlydisabled (path)) {//create Webpagehttphandler ihttph                 Andler handler = Webpagehttphandler.createfromvirtualpath (path); if (handler! = null) {sessionstateutil.setupsessionstate (context, handler); Replace the HttpForbiddenHandler context configured in Web. config.                 Remaphandler (handler);             }}}} else {string extension = Pathutil.getextension (pathvalue); foreach (String str4 in Registeredextensions) {if (string. Equals ("." + str4, extension, stringcomparison.ordinalignorecase)) {throw new Httpexc                 Eption (0x194, NULL); }             }         }     } }

Webpageroute also implemented Webpages Web site page address more user-friendly features, such as the need to take cshtml and vbhtml suffix can access the corresponding page, you can use filename/category/id such as address access, by adding XX. Mobile.cshtml can automatically switch to the mobile page function and so on. After this HttpHandler is created, the page is executed, and the base class for the webpages page is System.Web.WebPages.WebPage.

If we configure webpages:enabled to False in the Web. config of the webpages Web site, the HttpForbiddenHandler is found to be handling them again when accessing cshtml or vbhtml.

<appSettings>    <add key= "webpages:enabled" value= "false"/></appsettings>

Cannot provide this type of page

At this point, we have a general understanding of the relevant operating principles of the webpages framework. The webpages framework implements HttpModule and BuildProvider registrations through the Preapplicationstartmethodattribute features provided by asp.net4.0, rather than the usual web. config configuration file, the procedure described in this article does not is absolute, because this feature can be automatically identified and run by the ASP. For example, if you refer to System.Web.WebPages, you will perform the method of registering Webpagehttpmodule configured on them, and the startup methods on those assemblies have a judging mechanism to prevent repetition.

Relationship to the Razor view engine in ASP.

Razor is not tightly coupled with MVC, which can be detached from MVC or out of the webpage framework. There are also Preapplicationstartmethodattribute features on the System.Web.MVC assembly, where the startup classes in System.Web.WebPages and System.Web.WebPages.Razor are called directly to register the We Bpagehttpmodule and Razorbuildprovider, But MVC inherits the Webpagerazorhost class in System.Web.Razor to achieve its own unique mvcwebpagerazorhost, which is equivalent to adding new functions to work with MVC.

Just as there are many different view engines in MVC, the webpages framework does not necessarily use the razor engine, and we can implement our own buildprovider to define the webpage syntax and parse the build. NET assembly.


Personally, the webpages framework has abandoned WebForms's cumbersome and opaque programming in the context of a growing focus on web standards and front-end UIs, With great flexibility and the ability to take advantage of the ASP. NET's powerful class library, the backend framework model does not change, but it allows the ASP to have a fast programming experience similar to PHP and ASP. Tired of WebForms the output code of the bloated program, quickly learn webpages it:)

Asp. NET's operation principle and operation mechanism

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: 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.