Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create an ASP.NET5 MVC6 project

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to create an ASP.NET5 MVC6 project". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to create an ASP.NET5 MVC6 project.

First acquaintance of the project

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

We can see that the Web Forms\ MVC\ Web API check boxes can not be selected at this time. The original reason is that a lot of changes have been made in ASP.NET 5 to remove the Web Forms function and combine MVC, Web API, Web Pages and other functions together, so naturally these check boxes are not needed. In addition, because it is the CTP version, the creation of a unit test project is not provided at this time.

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

Note: the above image is a screenshot in the VS preview version. In the new version of RC, the default client build tool has become gulp (that is, the configuration file is gulpfile.js) instead of the original grunt.

The difference between the two pictures is very big. Let's analyze these differences one by one.

Project structure difference

From the illustration, we can see that in the root directory, not only the project file has changed from csproj to xproj, but also a lot of previous files (such as web.config) have been missing, but there are also many different files and folders. Let's list these different folder folders first, and then explain these contents one by one.

Project.json

Project.json is the core configuration file of the project. Examples are as follows:

{"webroot": "wwwroot", "version": "1.0.0 dependencies *", "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"]}}

As there are many detailed parameters in this file, please refer to http://go.microsoft.com/fwlink/?LinkID=517074 for details. Here we mainly explain the following three types of content.

Webroot

Webroot specifies the static file location for the web project and is currently the correct location for internal releases in this directory at release time (details can be found in the deployment release section). Note that the wwwroot directory with the Earth icon in the BookStore solution is the real folder path, and we can modify it, such as changing it to wwwroot1, then the value of the corresponding webroot should also be changed to wwwroot1, because the code in gulpfile.js needs to use this directory through project.webroot, so that all the front-end libraries managed by bower can be copied to the correct directory.

Assembly management

At the References node 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), while DNX 4.5.1 is the same full-featured version as the previous version, which is managed through the dependencies node.

At the first level, the dependencies node mainly defines the general assembly reference and version of the project, while different versions of the assembly are maintained by the dependencies node under each version of the framworks, such as:

"frameworks": {

"dnx451": {

"dependencies": {"log4net": "2.0.3"} / * log4net assemblies are introduced only in the full feature version * /

}

"dnxcore50": {}

}

The above two types of assemblies are maintained with smart prompts (including assembly name and version number). After defining the assembly you want to use and keeping it, the system will automatically download the required assembly from Nuget, or you can update all assembly references by right-clicking References and selecting Restore Packages. At the same time, you can still manage these assemblies through Nuget by right-clicking References.

Script event

The new version of VS2015 allows us to customize some Nodejs-based custom events to execute before and after the build solution, before and after downloading the assembly, and before and after updating the assembly. The definition node for this event in project.json is scripts. The example is as follows:

"scripts": {

"postrestore": ["npm install"], / / execute the npm install event before updating all assemblies

"prepare": ["gulp copy"]

/ / before opening the solution, execute the gulp task and call the install method of bower.

}

The specific event names are as follows:

Package.json

Package.json is the configuration file for the NPM manager, and because Nodejs is deeply integrated by default in VS2015, and NPM is the default package manager for Nodejs, all Nodejs-based packages are configured here. The default configuration of this profile is as follows:

{"name": "ASP.NET", "version": "0.0.0", "devDependencies": {"gulp": "3.8.11", / / gulp Task Manager "rimraf": "2.2.8" / / Recursive delete file nodejs package}} above generation

Rimraf in the code is a nodejs package for recursively deleting files. We can also refer to other plug-ins, like managing assemblies in the project.json file, managing various packages of front-end programs in the package.json file, such as jquery,bootstrap, etc., for example, to install an express package, we only need to add an express string key to the json file and select the version of the device. The NPM package is automatically downloaded and displayed under the Dependencies- > NPM node of the solution.

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

Bower.json

All front-end packages are configured in child bower.json files, such as jquery, bootstrap, angular, etc., which are managed in the same way as assemblies in project.json and npm packages in package.json, by declaring the name and version of the package under the dependencies node.

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

It is also important to have an exportsOverride node in bower.json, which extends the original bower's front-end file copy mechanism. By default, bower only copies files defined by the main node. But sometimes we have to copy more than these files, so the grunt-bower-task plug-in extends this feature to define the exportsOverride node, and its usage rules are as follows:

If the Bower package defines a main file node, copy it under wwwroot/lib.

If the main node defined by the Bower package is empty, copy the directory of the entire package to wwwroot/lib.

If an exportsOverride node is defined, only the files specified by that node are copied to the wwwroot/lib.

Notice the key/value defined in the exportsOverride node, where key represents the subdirectory under the package name of the file to be copied (that is, under wwwroot/lib), and value represents the source file directory or file. For example:

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

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

Gulpfile.js

Gulpfile.js is the configuration file for the gulp task manager, which by default clears all files in the wwwroot/lib directory (clean task) and then re-copies a copy from the bower_components directory (copy task).

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

Take the default configuration as an example. The configuration file registers two tasks, clean and copy, in the Task directory, and reexecutes the clean task by default after the VS solution clears and compiles, but we can also bind any execution point to the task. We can right-click the task-> bind-> before building, and then click the refresh button on the left side of the panel. At this point, the binding content will be saved synchronously in the * line of gulpfile.js, as follows:

/ / /

At this point, delete all the files in the wwwroot/lib directory, and then recompile the BookStore project, and automatically generate all the necessary files in the wwwroot/lib directory, that is, copy the various packages defined in Bower.json to this directory according to the configuration requirements.

Clean task

The main purpose of the clean task is to delete all the front-end files in the lib directory before compilation or to clean up the solution in order 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 file system eval ("var project =" + fs.readFileSync (". / project.json"); / / read project.json configuration file var paths = {bower: ". / bower_components/", lib: ". /" + project.webroot + "/ lib/"} Gulp.task ("clean", function (cb) {/ / register clean task rimraf (paths.lib, cb); / / Recursively delete all files in the lib directory})

Copy task

The copy task is very simple. Copy the qualified files in the bower_components directory to the lib directory and analyze them as follows:

Gulp.task ("copy", ["clean"], function () {/ / register copy task var bower = {/ / directory correspondence "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]) / / read source directory .pipe (gulp.dest (paths.lib + destinationDir)) / / copy to destination folder}})

Grunt task

In VS2015, although the Gulp build tool is supported by default, it also supports the Grunt build tool, which is similar to Gulp. To use Grunt, you need to refer to similar dependency packages. Examples are as follows:

{"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}

The grunt-bower-task in the above code is a grunt-based bower management plug-in that automatically executes the install command of bower to install the Bower package.

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

Gruntfile.js is the configuration file of the grunt task manager. To use grunt, you need to create a gruntfile.js file. By default, this configuration file only configures the task execution of the grunt-bower-task plug-in, which will read the bower.json configuration information and install the related packages to the specified directory through the bower:install command (the default is the wwwroot/lib directory set by targetDir.

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

Take the default configuration as an example. The profile registers a task named default, which is displayed in the panel (Alias Tasks list). The task is also the default task name of Grunt, but it does not define when the task will be executed, so at this time we can bind the task to an execution point. We can right-click the task-> bind-> before building, and then click the refresh button on the left side of the panel. At this point, the binding content will be saved synchronously in the * line of gruntfile.js, as follows:

/ / /

At this point, delete all the files in the wwwroot/lib directory, and then recompile the BookStore project, and automatically generate all the necessary files in the wwwroot/lib directory, that is, copy the various packages defined in Bower.json to this directory according to the configuration requirements. Tasks in Tasks are tasks analyzed from packages loaded in grunt.loadNpmTasks, such as bower.

Let's practice another example. If we want to compress the site.css file in the wwwroot/css/ directory (compressed to site.min.css) before compiling, we can install it as follows:

First, define a grunt plug-in in package.json that compresses the 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 plugin * /}}

Then under the bower sibling node under grunt.initConfig, add the following:

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

* re-register this plug-in with the following code:

Grunt.loadNpmTasks ('grunt-contrib-cssmin'); / * compress the css*/ so that you can see the cssmin task in the Task Runner Explorer panel and run it, but you can also add the task along with the default task to execute before the build. The code is as follows: /

In addition, give some examples, one for js compression and one for less compilation, the code is as follows:

/ * package.json*/ "grunt-contrib-uglify": "0.9.1", "grunt-contrib-less": "1.0.1" / * gruntfile.js*/ / * Compression 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 (compression) production: {options: {compress: true} Files: {'wwwroot/Styles/site.min.css':' wwwroot/Lesses/site.less'} / *... * / grunt.loadNpmTasks ('grunt-contrib-uglify') / * compress js*/ grunt.loadNpmTasks ('grunt-contrib-less'); / * compile less*/

Advice: do not bind the same task at multiple times.

Recommendation: grunt also has a plug-in for monitoring file modifications, such as changes to compatible css files. Once modified, call the css compression command. For more information, please refer to the grunt-contrib-watch plug-in.

Config.json

Config.json is the former web.config, but not as powerful as web.config has various types of configuration, in which the configuration of various functions is transferred to the Startup.cs file in the form of code; the other part of the information configuration content is saved in the config.json file in json format.

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

/ / Configuration = new Configuration () .AddJsonFile ("config.json") .AddEnvironmental variables () in the constructor of the Startup.cs class

Load the configuration file through the Configuration instance and save it in the Configuration property so that it can be used elsewhere, while the key value is defined by 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's not as convenient to use as web.config, but it's the only way to be compatible with other operating systems.

Note: in ASP.NET5, configuration information supports not only json format, but also ini, xml and other formats. For more information, please see the following configuration information management section.

Startup.cs

Startup.cs is the startup entry of the whole program, which is similar to Global.asax and plays the role of global configuration information like Global.asax files. Let's analyze several important functions of this document.

First initialize the basic configuration information in the constructor (see the configuration information management section for detailed configuration information). Note that the initialized configuration information here is bound to a Configuration attribute so that the other two methods can be used later. If you want to use it in other classes, you need to save the instance to another place (such as static variables).

The ConfigureServices method is the core of dependency injection. In the incoming parameter services of the method, the type definition defined in the default dependency injection is saved first, and then we can continue to register the type definition of dependency injection in this method. For more information on dependency injection, you can read the section on dependency injection.

At the same time, if some important functions need to be enabled, you also need to enable them here. For example, to add a Mvc module, you need to use the following call statement:

Services.AddMvc ()

The reason is that in the new version of ASP.NET 5, except for the most basic modules, most modules are purely componentized, which is called Middleware, and components need to be added before they can be used. For example, if you add an EF module, you need to call the

The services.AddEntityFramework () method.

The other Configure method, as its name implies, is where various Middleware components are configured. Generally speaking, the method of configuring a module is to call a method such as app.UseXXX (). If you use a static file processing flow, you can call the following statement:

App.UseStaticFiles ()

If you want to use the functionality of Mvc, you need to use the app.UseMvc method, and when you call these methods, you can configure and pass in the parameters of the response.

Note that the methods of type services.AddXXX () used in ConfigureServices and the methods of type app.UseXXX () used in the Configure method are extension methods, the AddXXX () method extends on the IServiceCollection interface, and the UseXXX () method extends on the IApplicationBuilder interface.

About the dependency injection mentioned in this file, and the three types of parameters in the Configure method: IApplicationBuilder, IHostingEnvironment, and ILoggerFactory.

Thank you for your reading, the above is the content of "how to create an ASP.NET5 MVC6 project". After the study of this article, I believe you have a deeper understanding of how to create an ASP.NET5 MVC6 project, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report