Interpretation of ASP. NET 5 & MVC6 series (2): First-profile project, interpretation of ASP. NET

Source: Internet
Author: User
Tags log4net

Interpretation of ASP. NET 5 & MVC6 series (2): First-profile project, interpretation of ASP. NET

Initial Project

Open VS2015, create a Web project, select ASP. NET Web Application, and select the ASP. NET 5 Website template in the pop-up window to create a project, as shown in the figure below:

We can see that at this time, the Web Forms \ MVC \ Web API check box cannot be selected, the original is because in ASP. NET 5 has made a lot of changes, removed the Web Forms function, and combined the MVC, Web API, and Web Pages functions, so these check boxes are naturally not needed. In addition, the unit test project has not yet been created because it is a CTP version.

The solution directory structure of the newly created Project in VS and the directory structure of the actual folder are as follows:

Note: In the VS preview version, in the new RC version, the default client build tool is changed to gulp (that is, the configuration file is gulpfile. js), rather than the original grunt.

The differences between the two charts are very large. Let's analyze these differences one by one.

Project structure difference

As shown in the figure, in the root directory, not only does the project file change from csproj to xproj, but also many earlier files (such as web. but there are a lot of different files and folders. We will first list these different file box folders and then explain them one by one.

Files/folders Function Description
Config. json Program configuration file, similar to web. config.
Project. json The main configuration of this project is mainly responsible for assembly and project deployment. Some functions are similar to the previous package. config.
Package. json Npm configuration file. npm is a Nodejs-based package manager.
Bower. json The configuration file of the Bower manager, which is used to manage the Package Manager of the front-end project.
Gulpfile. js It is the configuration file of gulp, and gulp is a Javascript Task Manager based on Nodejs. It is mainly used in ASP. NET5 to manage content in NPM and Bower.
Stratup. cs Program startup entry, similar to Global. asax.
Project_Readme.html The project description file is useless.
Wwwroot The storage directory of static resource files (such as css, images, and js.
Dependencies The dependency management packages of Bower and NPM.
References Assembly reference, similar to the previous one, but now there are versions (such as ASP. NET 5.0 and ASP. NET Core 5.0 ).

Project. json

Project. json is the core configuration file of the project, for example:

{ "webroot": "wwwroot", "version": "1.0.0-*", "dependencies": {  "Microsoft.AspNet.Diagnostics": "1.0.0-beta4",  "Microsoft.AspNet.Mvc": "6.0.0-beta4",  "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta4",  "Microsoft.AspNet.Server.IIS": "1.0.0-beta4",  "Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",  "Microsoft.AspNet.StaticFiles": "1.0.0-beta4",  "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta4",  "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",  "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta4",  "Microsoft.Framework.Logging": "1.0.0-beta4",  "Microsoft.Framework.Logging.Console": "1.0.0-beta4",  "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta4",  "Microsoft.Framework.ConfigurationModel.UserSecrets": "1.0.0-beta4" }, "commands": {  "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000",  "gen": "Microsoft.Framework.CodeGeneration" }, "frameworks": {  "dnx451": { },  "dnxcore50": { } }, "exclude": [  "wwwroot",  "node_modules",  "bower_components" ], "publishExclude": [  "node_modules",  "bower_components",  "**.xproj",  "**.user",  "**.vspscc" ], "scripts": {  "postrestore": [ "npm install", "bower install" ],  "prepare": [ "gulp copy" ] }}

Since the file has a lot of detailed parameters, For details, please refer to the http://go.microsoft.com/fwlink? LinkID = 517074. Here we will mainly explain the following three types of content.

Webroot

Webroot specifies the static file storage address of the web project, currently, it is used to describe the correct position of the internal release in the directory during the release (details can be found in the deployment release chapter ). Note that the BookStore solution contains the earth iconwwwrootThe directory is a real folder path. We can modify it, for example,wwwroot1, The corresponding webroot value should also be modifiedwwwroot1Because the code in gulpfile. js needs to passproject.webrootTo copy the front-end libraries managed by bower to the correct directory.

Assembly management

In the References section of the solution, we can see two categories: DNX 4.5.1 and DNX Core 5.0, among them, DNX Core 5.0 is what we call the cloud optimized version (that is, the cross-platform version that can be deployed in other operating systems), while DNX 4.5.1 is the same as the full-featured version of the previous version, these two versions of the Assembly aredependenciesNodes.

At level 1dependenciesNodes are used to define the General Assembly reference and version of the project.framworksUnder each versiondependenciesNode maintenance, such:

"Frameworks": {"dnx451": {"dependencies": {"log4net": "2.0.3"}/* only introduce log4net assembly in the full-featured version */}, "dnxcore50 ":{}}

The preceding two types of assembly have smart prompts (including the Assembly name and version number) during maintenance. After the Assembly is defined and maintained, the system automatically downloads the required assembly from Nuget. You can also right-click References and Select Restore Packages to update all Assembly References. You can also right-click the References to manage these sets through Nuget.

Script event

The new version of VS2015 allows us to execute custom events based on Nodejs before, after, and after the build solution, before, and after the Assembly is downloaded, and before, and after the Assembly is updated. The node defined for this event in project. json is scripts, for example:

"Scripts": {"postrestore": ["npm install"], // run the npm install event "prepare" before updating all the Assembly ": ["gulp copy"] // run the gulp task and call the install method of bower before opening the solution .}

The specific event name is as follows:

Timing Description
Prebuild Run before build
Postbuild Run after build
Prepack Run before packing
Postpack Run the following command after packing:
Prerestore Run the restoring packages command
Postrestore Run the restoring packages command

Package. json

package.jsonYesNPMThe configuration file of the manager is deeply integrated by default in VS2015.Nodejs, AndNPMAgainNodejsThe default package manager, so allNodejsThe packages must be configured here. The default configuration of this configuration file is as follows:

{"Name": "ASP. NET "," version ":" 0.0.0 "," devDependencies ": {" gulp ":" 3.8.11 ", // gulp Task Manager" rimraf ": "2.2.8" // recursively Delete the nodejs package of the file }}

In the above CoderimrafIs a nodejs package that recursively deletes files. We can also reference other plug-ins, suchproject.jsonFile Management assembly, inpackage.jsonFile to manage various packages of the front-end program, such as jquery and bootstrap. For example, to install an express package, you only need to add an express string key to the json file, the NPM package is automatically downloaded and displayed inDependencies->NPMNode.

Note: The installed package cannot be automatically removed (that is, the configuration cannot be removed from JSON). You need to right-click the package and manually uninstall it.

Bower. json

All front-end packages are configured with sub-bower. json files, such as jquery, bootstrap, and angular. the Assembly and package in json. the npm package in json is implemented by declaring the package name and version under the dependencies node.

We can declare an angular package here. After saving it, we can see that the angular has been automatically downloaded under the solution Dependencie-> Bower node. compile the project, you can see the angular folder and corresponding files in wwroot/lib.

Another exportsOverride node in bower. json is very important. It extends the front-end file copy mechanism of the original bower. By default, the bower will only copy files defined by the main node. But sometimes we need to copy more files, so the grunt-bower-task plug-in has extended this function and defined this exportsOverride node. Its usage rules are as follows:

If the Bower package defines the main file node, copy it to wwwroot/lib. If the main node defined in the Bower package is empty, copy the entire package directory to wwwroot/lib. If an exportsOverride node is defined, only the Files specified by the node are copied to wwwroot/lib.

Note: The key/value defined in The exportsOverride node, where key indicates the subdirectory under the package name of the target for file replication (that is, under wwwroot/lib), and value indicates the source file directory or file. For example:

"Bootstrap": {"js": "dist/js /*. * ", // copy all files under dist/js/to the" css ":" dist/css/* directory of wwwroot/lib/bootstrap/js /*. * "," fonts ":" dist/fonts /*. * "}," jquery ": {" ":" jquery. {js, min. js, min. map} "// convert jquery. js, jquery. min. js, jquery. min. copy the map file to the wwwroot/lib/jquery directory },

Note: similar to NPM, the configuration package in bower. json cannot be automatically removed. You need to uninstall the package from Bower and remove the related files from wwwroot/lib.

Gulpfile. js

Gulpfile. js is the configuration file of the gulp Task Manager. By default, the configuration filewwwroot/libClean all the files in the directory, and thenbower_componentsCopy a copy (copy task) in the directory ).

Modifications to the file configuration will affectTask Runner ExplorerAs shown in:

Taking the default configuration as an example, the configuration file registers two tasks in the Task directory, namely clean and copy. By default, the clean Task is re-executed after the VS solution clears the compilation, however, you can also bind the task to any execution time point. You can right-click the task and choose "bind"> "bind". Before building the task, click "refresh" on the left of the Panel, at this time, the bound content will be synchronously saved in gulpfile. the first line of JavaScript code is as follows:

/// <binding BeforeBuild='copy' Clean='clean' />

Delete all the files under the wwwroot/lib directory, and re-compile the BookStore project. Then, all required files will be automatically generated under the wwwroot/lib directory, that is, Bower. various packages defined in json are copied to this directory according to Configuration Requirements.

Clean task

The main function of the clean task is to delete all the front-end files in the lib directory before compilation or the solution is to re-copy the new files. The specific analysis is as follows:

Var gulp = require ("gulp"), // reference gulp rimraf = require ("rimraf"), // reference rimraf fs = require ("fs "); // reference the file system eval ("var project =" + fs. readFileSync (". /project. json "); // read the project. json configuration file var paths = {bower :". /bower_components/", lib :". /"+ project. webroot + "/lib/"}; gulp. task ("clean", function (cb) {// register the clean task rimraf (paths. lib, cb); // recursively delete all files in the lib directory });

Copy task

The copy task is simple. copy the files that meet the requirements under the bower_components directory to the lib directory and analyze them as follows:

Gulp. task ("copy", ["clean"], function () {// register the copy task var bower = {// directory ing "bootstrap ": "bootstrap/dist /**/*. {js, map, css, ttf, svg, woff, eot} "," bootstrap-touch-chain usel ":" bootstrap-touch-chain usel/dist /**/*. {js, css} "," hammer. js ":" hammer. js/hammer *. {js, map} "," jquery ":" jquery/jquery *. {js, map} "," jquery-validation ":" jquery-validation/jquery. validate. js "," jquery-validation-unobtrusive ":" jquery-validation-unobtrusive/jquery. validate. unobtrusive. js "} for (var destinationDir in bower) {gulp. src (paths. bower + bower [destinationDir]) // read the source directory. pipe (gulp. dest (paths. lib + destinationDir); // copy to target folder }});

Grunt task

In VS2015, although the Gulp build tool is supported by default, Grunt build tools are also supported. The usage is similar to that of Gulp. To use Grunt, similar dependency packages need to be referenced, example:

{"Version": "0.0.0", "name": "", "devDependencies": {"grunt": "0.4.5 ", // grunt task Manager "grunt-bower-task": "0.4.0" // grunt-based bower management plug-in }}

In the above Codegrunt-bower-taskIsgruntOfbowerManagement plug-in for Automatic ExecutionbowerOfinstallCommand to install the Bower package.

Note: The installed package cannot be automatically removed (that is, the configuration cannot be removed from JSON). You need to right-click the package and manually uninstall it.

Gruntfile. js is the configuration file of the grunt Task Manager. To use grunt, you need to create gruntfile. js file. By default, this configuration file only configures the task execution of the grunt-bower-task plug-in. The plug-in will read the bower. json configuration information.bower:installCommands are installed in the specified directory (the default is the wwwroot/lib directory set through targetDir.

Modifications to the file configuration will affectTask Runner ExplorerAs shown in:

Taking the default configuration as an example, the configuration file registers a task named default and is displayed in the panel (in the Alias Tasks list). This task is also the default Task Name of Grunt, however, it does not define when the task will be executed, so we can bind the task with an execution time point, and we can right-click the task-> bind-> before building, then, click the refresh button on the left side of the Panel. At this time, the bound content will be synchronously saved in gruntfile. the first line of JavaScript code is as follows:

/// <binding BeforeBuild='default' />

Delete all the files under the wwwroot/lib directory, and re-compile the BookStore project. Then, all required files will be automatically generated under the wwwroot/lib directory, that is, Bower. various packages defined in json are copied to this directory according to Configuration Requirements. The task in Tasks is the task analyzed in the package loaded from grunt. loadNpmTasks, such as bower.
Let's take another example. Suppose we need to compress the site.css file (compressed into site.min.css) in the wwwroot/css/directory before compiling. We can install the following method for operations:

First, define a grunt plug-in package. json that can compress CSS code:

{"Version": "0.0.0", "name": "", "devDependencies": {"grunt": "0.4.5", "grunt-bower-task ": "0.4.0", "grunt-contrib-cssmin": "0.12.2"/* New plug-in */}}

Add the following content under the bower peer node under grunt. initConfig:

/* Compress css */cssmin: {target: {options: {sourceMap: true,}, files: {/* output file path: original file path */'wwwroot/css/site.min.css ': 'wwwroot/css/site.css '}}}

Finally, register the plug-in. The Code is as follows:

Grunt. loadNpmTasks ('grunt-contrib-cssmin ');/* compress css */

In this way, you can see the cssmin Task in the Task Runner Explorer panel, and then run it. Of course, you can also add the Task and the default Task together for execution before compiling and building. The Code is as follows:

/// <binding BeforeBuild='default, cssmin' />

In addition, for some examples, one is for js compression and the other is for less compilation. The Code is as follows:

/* Package. json */"grunt-contrib-uglify": "0.9.1", "grunt-contrib-less": "1.0.1"/* gruntfile. js * // * compressed js */uglify: {target: {options: {sourceMap: true,}, files: {'wwwroot/Scripts/site. min. js': 'wwwroot/Scripts/site. js' }},/* compile less */less: {// development version (no compression) development: {options: {sourceMap: true}, files: {'wwwroot/Styles/site.css ': 'wwwroot/Lesses/site. less '}}, // production version (Compressed) production: {options: {compress: true}, files: {'wwwroot/Styles/site.min.css ': 'wwwroot/Lesses/site. less '}}}/*... */grunt. loadNpmTasks ('grunt-contrib-uglify ');/* compressed js */grunt. loadNpmTasks ('grunt-contrib-less ');/* compile less */

Suggestion: do not bind the same task in multiple periods.
Recommendation: grunt also has a plug-in for modifying monitoring files. For example, grunt is compatible with modifications to css files. Once modified, the css compression command is called. For details, seegrunt-contrib-watchPlug-ins.

Config. json

Config. json is the previous web. config, but no web. config has various types of configuration that are so powerful. The configuration of various functions is transferred to Startup in the form of code. the cs file is in; the other part of information configuration content is placed in config. the json file is saved in json format.

Note that the file information is not automatically loaded by default. Instead, you need to manually load the configuration information by yourself. The Code is as follows:

// Configuration = new Configuration (). AddJsonFile ("config. json"). AddEnvironmentVariables ();

Load the Configuration file through the Configuration instance and save it in the Configuration Attribute so that it can be used elsewhere. The key value during use is defined by level, for the following default content:

{ "AppSettings": {  "SiteTitle": "WebDemo01" }}

To obtain the link string, use the following key value:

var connString = Configuration.Get("AppSettings:SiteTitle");

It is no longer convenient to use web. config, but this is the only way to be compatible with other operating systems.

Note: In ASP. NET5, the configuration information not only supports json format, but also ini, xml and other formats. For details, see the subsequent configuration information management chapter.

Startup. cs

Startup.csIt is the startup entry of the entire program, similar to the Global. asax file, and serves as the Global configuration information. Let's analyze several important functions of this file.

First, initialize the basic configuration information in the constructor (for detailed configuration information, see the configuration information management chapter). Note that the initialized configuration information is bound toConfigurationAttribute, so that the other two methods can be used later. If you want to use them in other classes, you need to save the instance to other places (such as static variables ).

ConfigureServicesThe method is the core of dependency injection. In the input parameter services of the method, the type definition defined in the default dependency injection is saved first. Then, in this method, you can continue to register the type definition of dependency injection. For more information about dependency injection, see the dependency injection section.

To enable some important functions, you also need to enable them here. For example, to add the Mvc module, you need to use the following call statement:

services.AddMvc();

The reason is that in the new ASP. in NET 5, except for the most basic modules, most modules are purely componentized. Here, they are called Middleware. When using components, you must first add them to use them. For example, to add an EF module, you must call

Services. AddEntityFramework () method.

Another Configure method, as its name implies, is used to Configure various Middleware components. Generally, the method of the configuration module calls apps similar to that of the configuration module. useXXX (). If you use a static file processing process, you can call the following statement:

app.UseStaticFiles();

To use the Mvc function, you must use the app. UseMvc method. When calling these methods, you can configure and pass in response parameters.

Note: The services used in ConfigureServices. the AddXXX () method and the app used in the Configure method. the UseXXX () method is an extension method. The AddXXX () method is extended on the IServiceCollection interface, while the UseXXX () method is extended on the IApplicationBuilder interface.

The dependency injection mentioned in this file and the three types of parameters in the Configure method are IApplicationBuilder, IHostingEnvironment, and ILoggerFactory. We will explain in detail in subsequent chapters.

Others

You can view the web. config has also been removed. In RC, to reference the namespace in a unified manner, you must go to _ ViewStart. cshtml or _ GlobalImport. in the cshtml file, we will discuss it later.

We do not need to make any changes. F5 runs the project and will automatically open the homepage of the new website because IIS Express is used by default. If it is not IIS Express, read the subsequent compilation and deployment sections.

Introduction to scheme in the preceding json configuration file

For the definition of scheme in the preceding configuration file (including global. json, project. json, config. json, package. json, and bower. json) and js parameter configuration, visithttp://schemastore.org/json/.

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.