ASP. NET has no magic-beautifying the ASP. net mvc interface and using Bundle for static resource management, mvcbundle

Source: Internet
Author: User

ASP. NET has no magic-beautifying the ASP. net mvc interface and using Bundle for static resource management, mvcbundle

For an application, the importance of the interface is unambiguous, while the Web application interface is implemented using Html + Css and Javascript, ASP. net mvc is a framework used to build Web applications. Its interface is also implemented in Html. For some development teams, professional UI front-end engineers and backend engineers may exist in Web projects, front-end engineers may only understand the design and Html, but apply the designed Html to ASP. NET may need ASP. NET engineers.
This article describes how to apply the designed Web interface to ASP. net mvc and manage these resource files. First, let's take a look at the modified results:

  

    

The main contents of this chapter include:
● Material Selection
● ASP. net mvc interface layout and implementation
● Use BundleConfig for material resource management
○ Use bundle to classify Materials
○ Use Bundle to optimize resource files
○ Use wildcards and file version (min version) in Bundle
○ Using CDN
○ Caching in Bundle
○ Bundle rewrite the resource reference path in the style sheet
○ Custom Resource Transformation (Transform)
● Summary

Material Selection

This article introduces the Open-Source Topic Start Bootstrap-Clean Blog.
Clean Blog is a responsive topic of modern style. Based on bootstrap 4.0, it shows the Running Effect of Clean Blog:

  

Download the Clean Blog to your local device and import it to the My Blog project. The topic contains the corresponding style sheet, image, Js, Sample Page, and other files:

  

Note: Clean Bolg GitHub address: https://github.com/BlackrockDigital/startbootstrap-clean-blog

Interface layout and implementation of ASP. NET MVC

Clean Blog is a static Web interface composed of Html, Css, and Javascript files. It must be applied to ASP. net mvc, you only need to analyze its structure and then replace it with ASP one by one.. net mvc View.
Therefore, we need to analyze the page layout of the Clean Blog and My Blog application. For the Clean Blog, it is divided into three parts: navigation, content, and footer:

  

The default ASP. net mvc template used before My Blog is also divided into navigation, content, and footer:

  

For the above layout, the navigation and footer sections remain unchanged, only the content in the middle is changed, in ASP. net mvc provides a layout page mechanism to define the page layout and place unchanged content on the layout page. To change the page, you must first define the layout page:
Add a new layout page under the Views/Shared directory, copy the navigation and footer code in the Index page of the Clean Blog to the new layout page, including css and js references (note: you need to modify the path). The content of the page is replaced by the @ RenderBody () method:

  

Change the layout file specified in _ ViewStart. cshtml to the new CleanBlog layout file:

  

Finally, modify the corresponding content page by referring to the Clean Blog content page style. The following uses the "Contact Us" page as an example:

  

Running Effect (Note: The information submission function in the original topic is not implemented ):

  

  

 

Use BundleConfig to manage material resources

Through the above introduction, I learned how to set up page content through page layout. In addition to Html code, Web pages are also supported by css, JavaScript, and other files, however, these files are relatively scattered in ASP. NET has a Bundle mechanism dedicated to managing these resource files.
Bundle has the meaning of Bundle and package, while in ASP. in net mvc, it can actually bind a set of css or JavaScript, which can be categorized according to some features of resources. At the same time, it also adds some useful additional functions, such: file minimization, resource file version management, CDN acceleration, resource file caching, etc. The following describes how to use bundle to manage newly added material resources in the project.

Use bundle to classify Materials

To ensure that the page style is consistent, the style and script shared by the whole site are added when the layout file is created. The Clean Blog is based on Bootstrap4.0 and has some special content, as shown in, its instance code has been classified:

  

Styles mainly include the core styles of Bootstrap, the fonts used in the template, and the custom styles in the template. In addition to the JavaScript necessary for bootstrap, JavaScript also includes custom JavaScript. According to this classification rule, register a category in the BundleConfig type of App_Start/BundleConfig:

Style category:

  

Script category:

  

Note: It is recommended that the bundle address be prefixed with bundles to avoid conflicts with routing.
After completion, use the Bundle rendering style and script in the layout file:

  

Use Bundle to optimize resource files

Previously, resources were classified by Bundle. When multiple files exist under the same class of resources, the page can be completely introduced with only one code to make the code clearer, of course, the Bundle mechanism can optimize resource files while classifying resources.
There are two optimization points: FileRequest OptimizationAnd filesSize OptimizationThe former combines files of the same class into one file, and only needs to be requested once upon request, the latter deletes unnecessary characters in css and JavaScript and Abbreviations The variable names to reduce the file size.
When you use Bundle to manage resources, it will be automatically optimized in Release mode. You can also set BundleTable. EnableOptimizations to true for forced optimization, as shown in:

The following results are displayed during running:
1. Fewer requests:

  

2. Non-Minimal js files are minimized, such as clean-blog.js:

  

Note: The above request contains an error that cannot be found in the font file, which will be explained later.

Use wildcards and file version (min version) in Bundle

For some style or script components, it may be composed of multiple files. For example, the Jquery directory contains jquery. js and jquery. slim. js files:

  

Other jQuery components may be used in some complex applications, so there will be more resource files. To simplify Bundle's resource classification, when using Bundle to register a category, you can use wildcards to match multiple files at a time:

    

Note: The Bundle can recognize two types of wildcards, commonly used as "*". In addition, you can use "{version}" to match the file version. For more information about wildcards, see: https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification#using-the--wildcard-character-to-select-files
Directly use the * wildcard to match all files in the corresponding directory. The result is:

  

As you can see, there are more js files than the previous requests. These files are matched by wildcards, but note thatNo js file containing. min version is obtainedIn the same directory, clean-blog.js and jquery. js both have min versions minimized:

  

The Bundle mechanism is based on the debug/release mode or BundleTable. enableOptimizations attribute to determine whether the resource file is optimized, In the release mode (web. the debug attribute of compilation in config is true) or BundleTable. when EnableOptimizations is set to true, resource optimization is enabled. In addition to the multiple file bundle mentioned above, if the file list contains min version files, then, the min version file will be selected first.
Because the file name of a specific request cannot be seen in optimized mode, add a log output code to the clean-blog.min.js:

  

Then run the program in release mode and the following results will be obtained:

  

In addition to reducing requests, you can also see that the logs output the content added to the min version file, proving that the Bundle automatically selects the minimal version of the file when running in release mode.

Use CDN

CDN (Content Delivery Network), in order to improve the web response speed, one of the main optimization measures is to put static resources on the CDN, in this way, the user can obtain these resources from the nearest network node, which increases the resource acquisition speed and reduces the pressure on the application server, ASP. the Bundle in. NET can configure CDN for the corresponding resources, and the configuration also takes effect in the release mode:

  

To use CDN, follow these steps:
● Set the UseCdn attribute of bundles to true.
● The CDN path is introduced in the constructor when a Bundle object is created.
● Set the CdnFallbackExpression attribute of the Bundle object to determine whether the content loaded by CDN is correctly loaded. If not, the content in the Include object is loaded.

Running effect:

  

Setting the bundles. CdnFallbackExpression attribute to window. jQuery generates a code to determine whether the window. jQuery object exists. If it does not exist, obtain the server resource:

  

You can modify the CDN resource path to simulate that the CDN cannot be accessed. It automatically loads available resources:

  

CDN available resources reference: http://www.bootcdn.cn/

Cache in Bundle

In the Release or resource optimization mode, Bundle provides a caching mechanism for its managed resources. When the first time you access resources managed by Bundle, Bundle generates a unique identifier for each group of resources, then, cache the resource for one year by default:

  

When the resource changes, the unique identifier changes, and the original cached content automatically becomes invalid.

Bundle rewrite the resource reference path in the style sheet

In the previous introduction, there was always an error in the release mode, that is, the font file cannot be found because some external resources such as fonts or images will be introduced during style Writing, these resources are generally referenced using relative paths, but when ASP. when Bundle is used to Bundle style resources in. NET, the url address of the resource changes, resulting in incorrect addresses of referenced resources using the combination of addresses, as a result, resources cannot be loaded:

  

To solve this problem, Bundle provides a solution to override the style reference relative path. When registering a style table to the Bundle, you can add a CssRewriteUrlTransform object to the corresponding Style File, it is used to rewrite the referenced Url when Css files are optimized:

  

After the above Code is added, the running program will solve the problem that the font cannot be found:

  

Transform)

Resource transformation is an extensible Interface provided by the Bundle mechanism when optimizing resources. For example, the css Url rewriting described above is the expansion of resource transformation. The following interfaces must be implemented to implement resource transformation in Bundle:

The parameters in the interface represent the obtained virtual path and file content.
The following is a resource converter that Inserts custom content into css to introduce how to implement custom expansion of resource transformation:
Implement the IItemTransform interface and append ". test {color: red;}" style to the style file:

  

Apply the converter to the corresponding file using the Include method:

  

The running result shows that the corresponding content has been added to the final style file:

  

Note: The IItemTransform interface is called before resource optimization. Therefore, the spaces and semicolons In the content added in this example are all optimized and deleted, therefore, you must pay attention to resource optimization when using IItemTransform for expansion.
In addition, the Bundle has another extended interface, IBundleTransform, which defines a method for converting the corresponding file of the Bundle:

  

Implement the Process interface and add "hello selim" to the response content ":

  

BundleTransform must be added to the Bundle's Transforms attribute:

  

Running result:

  

Compared with ItemTransform, content processed by BundleTransform will not be optimized.

Summary

This chapter describes how to apply existing Web styles to ASP. net mvc and focuses on the Bundle mechanism for static resource management in ASP. net mvc. In addition to classifying resource files, the Bundle mechanism also provides advanced functions such as resource file optimization, CDN, and cache. Reasonable Use of Bundle can make the project code clearer and improve the application performance.

Refer:
Https://github.com/BlackrockDigital/startbootstrap-clean-blog
Https://html.com/attributes/
Https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification
Https://www.codeproject.com/articles/842961/introducing-dynamic-bundles-for-asp-net-mvc
Https://stackoverflow.com/questions/11355935/mvc4-stylebundle-not-resolving-images #
Http://www.bootcdn.cn/
Http://www.tutorialsteacher.com/mvc/scriptbundle-mvc
Https://www.codeproject.com/Articles/728146/ASP-NET-MVC-bundles-internals
Https://blogs.msdn.microsoft.com/rickandy/2011/05/21/using-cdns-and-expires-to-improve-web-site-performance/

Link: http://www.cnblogs.com/selimsong/p/8589175.html

ASP. NET has no magic-directory

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.