Analysis of operation Principle of ASP. NET webpages frame (turn)

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, written in a way closer to PHP and previous ASP, and using 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 = Database.open ("startersite"var users = db. Query ("select * from UserProfile"new WebGrid (users);} <! DOCTYPE html> @grid. Gethtml () </body>          

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=2.0.0.0, Culture=neutral, publickeytoken=31bf3856ad364e35"/> <add assembly="System.Web.WebPages.Deployment, version=2.0.0.0, Culture=neutral, publickeytoken=31bf3856ad364e35"/> <add assembly="System.Web.WebPages.Deployment, version=1.0.0.0, Culture=neutral, publickeytoken=31bf3856ad364e35"/> </assemblies></compilation>"*.cshtm"Verb="*"Type="System.Web.HttpForbiddenHandler"Validate="True"/><add path="*.cshtml"Verb="*"Type="System.Web.HttpForbiddenHandler"Validate="True"/><add path="*.vbhtm "Verb= * "Type=" system.web.httpforbiddenhandler "Validate=" true "*.vbhtml  "Verb= * "Type=" system.web.httpforbiddenhandler "Validate=" true            

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, this feature configures a static method to execute automatically before the program starts, with the following features: [assembly: Preapplicationstartmethod (typeof (Preapplicationstartcode), "Start")], view the Start method of the Preapplicationstartcode class, It calls the Startcore method, and Startcore calls the Loadwebpages method, where the function is to get all the DLLs associated with the webpages framework and get the configuration on those DLLs. Preapplicationstartmethodattribute features corresponding to the startup method and all execution, the DLL with this feature has System.Web.WebPages, System.Web.WebPages.Razor and Webmatrix.webdata, we focused on the top two.

 private static  void Loadwebpages (version version) 
{
Ienumerable<assembly> assemblies = enumerable.select< AssemblyName, Assembly> (assemblyutils.getassembliesforversion (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:

PublicStaticClassPreapplicationstartcode {//FieldsPrivateStaticbool_startwascalled;// Methods public static void Start () { _startwascalled) {_startwascalled = true ".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

PublicStaticClassPreapplicationstartcode {//FieldsPrivateStaticbool_startwascalled;//MethodsPublicStaticvoidStart () {if (!_startwascalled) {_startwascalled =True "cshtml "); Webpagehttphandler.registerextension ( "vbhtml ");         Pageparser.enablelongstringsasresources = false//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.

void Onapplicationpostresolverequestcache (objectnew httpcontextwrapper ((HttpApplication) sender).   Context); new Webpageroute (). Dopostresolverequestcache (context); }
InternalvoidDopostresolverequestcache (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)] =MatchString path ="~/" +Match. Matchedpath;//Whether the webpages:enabled is explicitly configured in the Web. config of the webpages websiteif (!webpagesdeployment.isexplicitlydisabled (path)) {//Create Webpagehttphandler IHttpHandler handler =Webpagehttphandler.createfromvirtualpath (path);if (Handler! =Null) {sessionstateutil.setupsessionstate (context, handler);//Replace the HttpForbiddenHandler configured in Web. configContext. Remaphandler (handler); } } }else { string extension = pathutil.getextension (pathvalue); foreach (string str4 in registeredextensions) { if (string. Equals ("." + str4, extension, stringcomparison.ordinalignorecase)) { throw new HttpException (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.

Conclusion

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

Analysis of operation Principle of ASP. NET webpages frame (turn)

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.