Interpreting ASP 5 & MVC6 Series (2): Initial knowledge Project

Source: Internet
Author: User
Tags file copy

Original: Interpretation of ASP. 5 & MVC6 Series (2): Initial knowledge Project

Initial Knowledge Project

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

As we can see, the Web forms\mvc\web API check box is not available at this time because a lot of changes have been made in ASP. NET 5, removing the web Forms feature, and the MVC, Web API, Web pages feature together, So naturally you don't need these check boxes. In addition, due to the CTP version, there is currently no unit test project to provide the creation.

The new project created in the VS solution directory structure and the actual folder directory structure are as follows:

Note: In the VS Preview version, in the new version of RC, the default client build tool becomes gulp (that is, the configuration file is Gulpfile.js), not the original grunt.

The difference between the two graphs is very large, so let's analyze these differences.

Project Structure Differences

From the diagram, we can see that in the root directory, not only the project files from csproj to Xproj, but also many of the previous files (such as Web. config), but also many different files and folders, we first listed these different file box folders, and then one by one to explain the content.

Files/Folders function Description
Config.json The configuration file for the program, similar to Web. config.
Project.json The main configuration of the project, mainly responsible for the assembly, project deployment and so on. Some features are similar to the previous package.config.
Package.json NPM configuration file, NPM is a Nodejs-based package manager.
Bower.json Bower Manager's configuration file, Bower is a package manager dedicated to managing front-end projects.
Gulpfile.js is a gulp configuration file, Gulp is a Nodejs-based JavaScript Task Manager that is primarily used to manage content in NPM and Bower in Asp.net5.
Stratup.cs The program launches the entry, similar to Global.asax.
Project_readme.html Project documentation, no use.
Wwwroot A storage directory for static resource files (such as CSS, pictures, JS).
Dependencies Dependency Management Packs for Bower and NPM.
References The assembly reference is similar to the previous one, but now has the version (such as ASP. NET 5.0 and ASP. NET Core 5.0).
Project.json

Project.json is the core configuration file for the project, as shown in the following example:

{"Webroot": "Wwwroot", "Version": "1.0.0-*", "dependencies": {"Microsoft.AspNet.Diagnostics": "1.0.0-bet A4 "," MICROSOFT.ASPNET.MVC ":" 6.0.0-beta4 "," Microsoft.AspNet.Mvc.TagHelpers ":" 6.0.0-beta4 "," Micros Oft. AspNet.Server.IIS ":" 1.0.0-beta4 "," Microsoft.AspNet.Server.WebListener ":" 1.0.0-beta4 "," Microsoft.aspnet.s Taticfiles ":" 1.0.0-beta4 "," Microsoft.AspNet.Tooling.Razor ":" 1.0.0-beta4 "," Microsoft.Framework.Configurat Ionmodel.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.b Rowserlink.loader ":" 14.0.0-beta4 "," Microsoft.Framework.ConfigurationModel.UserSecrets ":" 1.0.0-beta4 "}," C Ommands ": {" Web ":" Microsoft.AspNet.Hosting--server Microsoft.AspNet.Server.WebListener--server.urls Http://loca       lhost:5000 ", "Gen": "Microsoft.Framework.CodeGeneration"}, "Frameworks": {"dnx451": {}, "Dnxcore50": {}}, "Exclude": ["Wwwroot", "Node_modules", "bower_components"], "publishexclude": ["No        De_modules "," bower_components "," **.xproj "," **.user "," **.VSPSCC "]," scripts ": { "Postrestore": ["NPM Install", "Bower Install"], "Prepare": ["Gulp Copy"]}}

Due to the detailed parameters of this file, please refer to http://go.microsoft.com/fwlink/?LinkID=517074 for more details, here we mainly explain the following 3 types of content.

Webroot

Webroot is a static file address that specifies the Web project, and is currently the correct location for internal publishing in the directory at the time of publication (details can be found in the Deployment Release section). Note that the bookstore solution with the earth icon wwwroot directory is the real folder path, we can modify it, such as modify it to wwwroot1 , then the corresponding Webroot value should also be modified to wwwroot1 , because the Gulpfile.js code to pass project.webrootto use the directory so that you can copy the Bower managed front-end libraries to the correct directory.

Assembly Management

At the References node point of the solution, we see two categories: DNX 4.5.1 and DNX Core 5.0, where DNX Core 5.0 is what we call the cloud-optimized version (that is, a cross-platform version that can be deployed under other operating systems), and DNX The 4.5.1 is the same full-featured version as the previous version, and the two versions of the assemblies are dependencies managed through the nodes.

In a first-level dependencies node, the primary is to define a generic assembly reference and version of the project, while the different versions of the assembly are framworks maintained under each version of the dependencies node, such as:

"frameworks": {    "dnx451": {        "dependencies": {"log4net": "2.0.3"} /* 只在全功能版中引入log4net程序集*/    },    "dnxcore50": { }}

Both types of assemblies are maintained with smart hints (including the assembly name and version number), which automatically downloads the required assemblies from NuGet when you have defined the assemblies you want to use, and you can also right-click References to select the Restore Packages to update all assembly references. You can still manage these assemblies through NuGet in the form of right-click References.

Script Events

The new version of VS2015 allows us to customize some Nodejs-based custom events before, after, and after the build solution, before and after the assembly is downloaded, before the assembly is updated, and later. The definition node for this event in Project.json is scripts, as shown in the following example:

"scripts": {    "postrestore": [ "npm install" ],  // 在更新所有的程序集之前执行npm install事件    "prepare": [ "gulp copy" ]    // 在打开解决方案之前,执行gulp任务,调用bower的install方法。}

The specific event name is as follows:

Timing Description
Prebuild Execute before Building
PostBuild Execute after Build
Prepack Packing prior to execution
Postpack Packing after execution
PreRestore Restoring packages prior to execution
Postrestore Restoring packages after execution
Package.json

package.jsonIs the NPM manager's profile, because in VS2015 the default is a deep integration Nodejs , but NPM also Nodejs the default Package manager, so all based Nodejs packages are configured here. The default configuration for this configuration file is as follows:

{    "name": "ASP.NET",    "version": "0.0.0",    "devDependencies": {        "gulp": "3.8.11",//gulp任务管理器        "rimraf": "2.2.8" // 递归删除文件的nodejs包    }}

In the above code rimraf is a recursive delete file Nodejs package, we can also refer to other plug-ins, like a project.json file in the administrative assembly, in the package.json file to manage the front-end program of various packages, such as jquery,bootstrap, etc. For example, to install an express package, simply add an express string key to the JSON file and select the version of the device, and the NPM package will be downloaded automatically and displayed under the solution's Dependencies->NPM node.

Note: Packages that have already been installed cannot be removed automatically (that is, you cannot remove the configuration in JSON), you need to right-click to execute the package, and manually uninstall it.

Bower.json

All front-end packages are configured in sub-Bower.json files, such as jquery, Bootstrap, angular, and so on that you need, It is managed in the same way as the Project.json assembly and the NPM package in Package.json, by declaring the package name and version under the Dependencies node.

We can declare a angular package here, save it can be seen in the solution Dependencie->bower node under the angular has been automatically downloaded, compile the project, you can see in the wwroot/ Lib can also see the angular folder and the corresponding files.

There is also a exportsoverride node in Bower.json, which extends the original Bower copy mechanism of the front-end file, and by default bower copies only the files defined by the main node. But sometimes the files we want to copy may be more than that, so the Grunt-bower-task plugin expands the feature and defines the Exportsoverride node with the following rules:

    1. If the Bower package defines the main file node, it is copied to Wwwroot/lib.
    2. If the main node defined by the Bower package is empty, the entire package directory is copied to wwwroot/lib.
    3. If the Exportsoverride node is defined, only the file specified by the node is copied to Wwwroot/lib.

Note that the key/value defined in the Exportsoverride node, where key represents the subdirectory under the package name for the file copy target (that is, wwwroot/lib), value represents the source file directory or file. For example:

"bootstrap": {    "js": "dist/js/*.*", //将dist/js/下的所有文件,复制到wwwroot/lib/bootstrap/js目录下    "css": "dist/css/*.*",    "fonts": "dist/fonts/*.*"},"jquery": {    "": "jquery.{js,min.js,min.map}" // 将jquery.js,jquery.min.js,jquery.min.map文件复制到wwwroot/lib/jquery目录下},

Note: Similar to NPM, the configured package in Bower.json cannot be removed automatically, it needs to be unloaded from Bower and the related files removed from the wwwroot/lib.

Gulpfile.js

Gulpfile.js is the configuration file for the Gulp Task Manager, which, by default, wwwroot/lib clears all files under the directory (Clean Task) and then re bower_components -copies a copy from the directory (copy task).

Changes to this file configuration will affect the display in VS Task Runner Explorer , as shown in:

As an example of the default configuration, the profile registers two tasks under the task directory, clean and copy, and by default re-executes the cleanup task after the VS solution clears compilation, but we can also bind the task to any one execution point in time, and we can right-click the task--bind- > Before the build, and then click the Refresh button on the left side of the panel, the bound content will be saved in the first line of Gulpfile.js, the code is as follows:

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

At this point, deleting all the files in the Wwwroot/lib directory and then recompiling the bookstore project will automatically generate all the required files in the Wwwroot/lib directory, and the various packages defined in Bower.json will be copied to the directory according to the configuration requirements.

Clean task

The primary role of the clean task is to remove all front-end files from the Lib directory before compiling or cleaning the solution so that the new files can be copied again. The specific analysis is as follows:

var gulp = require("gulp"), // 引用gulp  rimraf = require("rimraf"),// 引用rimraf  fs = require("fs");  //引用文件系统eval("var project = " + fs.readFileSync("./project.json"));  //读取project.json配置文件var paths = {  bower: "./bower_components/",  lib: "./" + project.webroot + "/lib/"};gulp.task("clean", function (cb) {  //注册clean任务  rimraf(paths.lib, cb);  // 递归删除lib目录下的所有文件});
Copy Task

Copy task is very simple, the bower_components directory under the conditions of the File replication Lib directory, analyzed as follows:

gulp.task("copy", ["clean"], function () {  // 注册copy任务  var bower = { // 目录对应关系    "bootstrap": "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}",    "bootstrap-touch-carousel": "bootstrap-touch-carousel/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])  // 读取源目录      .pipe(gulp.dest(paths.lib + destinationDir));  //复制到目标文件夹  }});
Grunt Tasks

VS2015, although the Gulp build tool is supported by default, it also supports grunt build tools, which are similar to gulp, using grunt and referencing similar dependency packages, as in the following example:

{    "version": "0.0.0",    "name": "",    "devDependencies": {        "grunt": "0.4.5", //grunt任务管理器        "grunt-bower-task": "0.4.0" // 基于grunt的bower管理插件    }}

The code above grunt-bower-task is a grunt management plug-in that is used to bower automate bower install commands to install the Bower package.

Note: Packages that have already been installed cannot be removed automatically (that is, you cannot remove the configuration in JSON), you need to right-click to execute the package, and manually uninstall it.

Gruntfile.js is the Grunt Task Manager configuration file, to use grunt, you need to create a gruntfile.js file, by default, the configuration file only configures the Grunt-bower-task plug-in task execution, the plug-in will read the Bower.json configuration information, the relevant Packages bower:install are installed in the specified directory by command (by default, the Wwwroot/lib directory is set by TARGETDIR.

Changes to this file configuration will affect the display in VS Task Runner Explorer , as shown in:

With the default configuration as an example, the profile registers a task named default that is displayed in the Panel (Alias tasks list), which is also the default task name for grunt, but does not define when the task is executed, so we can bind the task to an execution point in time , we can right-click the task---bind---before the build, then at the left of the TAP Panel Refresh button, then the binding content will be saved in the first line of Gruntfile.js, the code is as follows:

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

At this point, deleting all the files in the Wwwroot/lib directory and then recompiling the bookstore project will automatically generate all the required files in the Wwwroot/lib directory, and the various packages defined in Bower.json will be copied to the directory according to the configuration requirements. The task in tasks is a task, such as Bower, that is analyzed from a package contained in Grunt.loadnpmtasks.
Let's practice one more example, assuming that we want to compress the Site.css file in the wwwroot/css/directory (compressed into site.min.css) before compiling it, we can do this in the following way:

First, define a grunt plugin 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"  /*新的插件*/  }}

Then below the Bower sibling node under Grunt.initconfig, add the following:

/*压缩css*/cssmin: {    target: {        options: {            sourceMap: true,        },        files: {            /*输出文件路径:原始文件路径*/            'wwwroot/css/site.min.css': 'wwwroot/css/site.css'        }    }}

Finally, register this plugin with the following code:

grunt.loadNpmTasks('grunt-contrib-cssmin'); /*压缩css*/

This allows you to see the Cssmin task in the Task Runner Explorer panel and then run it, and of course you can also add the task and the default task to the build before compiling it. The code is as follows:

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

In addition, in giving some examples, one is for JS compression, one for less compile, the code is as follows:

/*package.json*/"grunt-contrib-uglify": "0.9.1","grunt-contrib-less": "1.0.1"/*gruntfile.js*//*压缩js*/uglify: {    target: {        options: {            sourceMap: true,        },        files: {            'wwwroot/Scripts/site.min.js': 'wwwroot/Scripts/site.js'        }    }},/*编译less*/less: {    //开发版(无压缩)    development: {        options: {            sourceMap: true        },        files: {            'wwwroot/Styles/site.css': 'wwwroot/Lesses/site.less'        }    },    //生产版(压缩)    production: {        options: {            compress: true        },        files: {            'wwwroot/Styles/site.min.css': 'wwwroot/Lesses/site.less'        }    }}/*...*/grunt.loadNpmTasks('grunt-contrib-uglify');  /*压缩js*/grunt.loadNpmTasks('grunt-contrib-less');   /*编译less*/

Recommendation: Do not bind the same task over multiple periods.
Recommendation: Grunt also has a plug-in for monitoring file changes, such as the compatibility of CSS file changes, once modified to call the CSS Compression command, for details, refer to the grunt-contrib-watch plugin.

Config.json

Config.json is the previous web. config, but no web. config is as powerful as the various types of configurations, and the configuration of the various functions is transferred to the Startup.cs file in the form of code, and the other part of the information configuration is placed in the Config.json file with JS On the format to save.

Note that the information for this file is not loaded automatically by default, but instead it needs to be loaded manually by itself, with the following code:

//Startup.cs类的构造函数中Configuration = new Configuration()                .AddJsonFile("config.json")                .AddEnvironmentVariables();

The configuration file is loaded through a configuration instance and saved in the configuration property so that it can be used elsewhere, while the key value at the time of use is defined by the hierarchy as follows:

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

To get the link string, you need to use the following key value:

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

It is easy to use without the Web. config, but only for compatibility with other operating systems.

Note: In Asp.net5, the configuration information is not only supported in JSON format, but also in INI, XML and other formats, please refer to the subsequent Configuration information Management section for details.

Startup.cs

Startup.csis the startup entry for the entire program, similar to Global.asax, and the role of global configuration information, like the Global.asax file. Let's analyze several important functions of the file.

First initialize the underlying configuration information in the constructor (refer to the Configuration Information Management Section for detailed configuration information), and note that the initialization configuration information here is bound to an Configuration attribute so that the other two methods are used later, if you want to use it in other classes, You need to save the instance to a different location (such as a static variable).

ConfigureServicesMethod is the core of the dependency injection, in the method's incoming parameter services, first save the default dependency injection definition of the type definition, and then in this method, we can continue to register the dependency injection of the type definition, about the dependency injection details, you can read the dependency injection chapter.

At the same time, some important functions need to be opened, also need to be opened here, such as the addition of MVC module, you need to use such as cut sentence:

services.AddMvc();

The reason is because, in the new version of ASP. NET 5, in addition to the most basic modules, the majority of modules are purely component, this is called middleware, and the component in use when the first need to add the module before it can be used. For example, if you add an EF module, you need to call

services.AddEntityFramework()方法。

And another configure method, as the name implies is the configuration of various middleware components, in general, the method of configuring the module is to invoke similar apps. Usexxx () Such a method, such as using a static file processing process, call the following statement:

app.UseStaticFiles();

If you want to use MVC functionality, you need to use the app. The Usemvc method allows you to configure and pass in the parameters of the response when these methods are called.

Note that the method of services.addxxx () type used in Configureservices and the app.usexxx () type used in the Configure method are extension methods, addxxx () The method is extended on the Iservicecollection interface, while the Usexxx () method is extended on the Iapplicationbuilder interface.

For the dependency injection mentioned in this file, as well as the parameters of the 3 types in the Configure method: Iapplicationbuilder, Ihostingenvironment, iloggerfactory; we will explain in detail in the following chapters.

Other

Through the view, you can find that the views directory of the Web. config is also removed, in the RC version, to unify the reference namespace, you need to viewstart.cshtml or globalimport.cshtml file, We'll talk about the next chapters.

We do not have to make any changes, F5 run the project can run, because the default is IIS Express, so the new site will automatically open the first page. If it is not IIS Express, please read the subsequent compilation and deployment chapters.

Scheme Introduction to the above JSON configuration file

For a scheme definition of the above configuration file (including Global.json, Project.json, Config.json, Package.json, Bower.json), and the definition of the JS parameter configuration, please visit http://schemastore.org/json/ for review.

Recommended Information:

    1. beiyuu.com/grunt-in-action/
    2. Http://www.it165.net/pro/html/201503/35652.html
Synchronization and recommendations

This article has been synchronized to the Catalog index: Interpreting ASP. & MVC6 Series

Interpreting ASP 5 & MVC6 Series (2): Initial knowledge Project

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.