ASP. NET Core 2.0: III. project structure, asp. netcore

Source: Internet
Author: User

ASP. NET Core 2.0: III. project structure, asp. netcore

In this chapter, let's take a look at the project structure of ASP. NET Core 2.0 in comparison to the ASP. NET Framework version. (This article will try its best to make it easier to learn and understand .)

Pay attention to the differences and prepare for project migration.

Create a project and select a type

Create a project. If you select. NET Core, the following types are optional: Console, empty project of ASP. NET Core, and Web API

We chose ASP. NET Core Web App (MVC). The project that uses Razor pages is not marked with MVC.

 

Project Structure

Shows the structure of the newly created Project. the Framework Version of. NET is similar. Now, we will introduce them one by one based on the number tags shown in the figure (Controller and Model will not be introduced, and View will introduce several special views separately ).

Follow the numbers to give a brief introduction one by one. First, let's take a look at what is used, and the subsequent articles will make a detailed study.

During the introduction, I will compare the familiar ASP. NET Framework version for easy understanding.

① Dependencies dependency

There are two main parts: NuGet and SDK. Currently, only one of these two parts is available.

Nuget:

Include Microsoft. AspNetCore. All. expand it to see MVC, Razor, EF, and SQLLite,

Officially speaking: it includes

  • All packages supported by the ASP. NET Core team.
  • All packages supported by Entity Framework Core.
  • Internal and third-party dependencies used by ASP. NET Core and Entity Framework Core.

Suddenly, this is a very big and comprehensive package. It is a little different from the previous modularization, and it is very uncomfortable to let your project reference some useless assembly for no reason.

In fact, these assemblies will not appear in the deployment package along with the release of the project, not only those that are not referenced, but also those that are referenced. these already exist in the deployment environment, so the release package will not become larger but will become smaller, don't worry.

SDK:

The SDk contains Microsoft. NETCore. App, which is part of the. NET Core library. That is.NETCoreAppFramework. It depends on smallerNETStandard.Library.

Compared with Microsoft. AspNetCore. All, it also contains some assembly, but it seems to be more "Basic.

Similarities and Differences

Most of Microsoft. AspNetCore. All is an assembly starting with Microsoft. Most of Microsoft. NETCore. App is familiar with system. XXX.

The relationship between the two is like ASP. NET and. NET. Here Asp. NetCore is relative to. Net Core.

The SDK is also a big and complete set. during deployment, the reference in the SDK will not appear in the deployment package, for example, is it very streamlined?

 

② LaunchSettings. json

As the name suggests, this is a STARTUP configuration file in json format. You can see through the above project structure that common config files in xml format such as web. config or app. config cannot be found,

They are all json. Open this json file and check whether it is easy to explain one item. Later, we found that vs7 7 in windows has a graphical configuration interface (right-click the current project-> properties-> debugging ),

It is too troublesome to introduce them one by one.

The Web server configurations in the figure below are familiar with URL, identity authentication, SSL, and other configurations.

The above part of the figure corresponds to the two configurations defined in the json profiles, respectively named by IIS Express and by the current project name HelloCore.

Switching the configuration items under this option will also change, equivalent to two pages. The configuration on each page corresponds to the corresponding node in json.

 

③ _ Layout. cshtml

Layout templates, simply put, all pages using this template have a roughly consistent layout,

For example, the structure of our pages is often as follows:

Headers, Footer, and Navigation are basically unchanged. Open _ Layout. cshtml and we can see a @ RenderBody () identifier, which is actually used to define the Content part,

The page that inherits this template only needs to provide this part of content.

Of course, there are also common identifiers such as @ RenderSection ("Scripts", required: false, the page that references this template can include references to specific JS of this page in the corresponding Section.

To reference this template, you only need to configure the following on the top.

@{    Layout = "~/Views/Shared/_Layout.cshtml";}

Is it troublesome to configure each page? ⑥ ViewStart. cshtml will help.

④ _ ValidationScriptsPartial. cshtml
<environment include="Development">    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script></environment>

On this page, you can see some such references. As the name suggests, validation is used for verification. We often see such pages.

@ Section Scripts {@ await Html. PartialAsync ("_ ValidationScriptsPartial ")}

Note: The default _ Layout template is not referenced, because not all pages require input operations.

Set the verification method in Model

[Required (ErrorMessage = "the user name cannot be blank! ")] [Display (Name =" UserName ")] public string UserName {get; set;} [EmailAddress (ErrorMessage =" Incorrect Email format! ")] [Required] [Display (Name =" EMail ")] public string EMail {get; set ;}

Add verification on the page:

<div asp-validation-summary="All" class="text-danger"></div><div class="form-group">    <label asp-for="Email"></label>    <input asp-for="Email" class="form-control" />    <span asp-validation-for="Email" class="text-danger"></span></div>

There are still a lot of details about validation. Here we will give a rough introduction to this article.

⑤ _ ViewImports. cshtml

Let's not talk about this first. In other words, a Web. config that disappears is the one in the View directory of the MVC project of the Framework version.

When you reference a Model in a View, we can add these references in this config to avoid writing using...

  <system.web.webPages.razor>    

Open _ ViewImports. cshtml now,

@using HelloCore@using HelloCore.Models@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The above functions are actually implemented here.

In particular, there is an additional @ addTagHelper than the original MVC.

In the above validation, we have seen such code

    <label asp-for="Email"></label>    <input asp-for="Email" class="form-control" />    <span asp-validation-for="Email" class="text-danger"></span>

We wrote it like this.

@Html.LabelFor(m => m.EMail)@Html.EditorFor(m => m.EMail)@Html.ValidationMessageFor(m=>m.EMail)

It seems that the TagHelper and HtmlHelper are a bit like each other. For more information, see the following sections.

⑥ ViewStart. cshtml

This is just one sentence,

@{    Layout = "_Layout";}

The content on this page will be executed before all views are executed. Now this sentence is a default Layout template for all views.

So write in View like this

@{    Layout = null;}

And write in this way

@{}

The first is to tell this View that no template is used.

The second method is to do nothing, so it uses the template specified in _ ViewStart. cshtml.

 

Of course, the function of this _ ViewStart. cshtml is not just to write such a sentence, we can also write some other content that requires "general" Execution here.

7. wwwroot

The name seems to be the default root directory of the IIS website. It contains all the "front-end" static files, css, image, JS, and a folder named lib.

The default content in lib is bootstrap and jquery.

In Startup, a non-parameter UseStaticFiles () method is called to mark this directory to the website root directory.

public void Configure(IApplicationBuilder app, IHostingEnvironment env){    //.....            app.UseStaticFiles();    //.....}

The path of the specific static file and related custom configuration, authorization, and so on are studied in detail.

⑧ Appsettings. json and appsettings. Development. json

This is the Web. config file of the original framework Version MVC.

However, this is concise enough. By default, there are only a few words about log configuration,

Of course, we need to configure more than this in normal projects. For example, database connection

{  "ConnectionStrings": {    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"  },  "Logging": {    "IncludeScopes": false,    "LogLevel": {      "Default": "Warning"    }  }}

 

Bundleconfig. json

The default file content is as follows:

[  {    "outputFileName": "wwwroot/css/site.min.css",    "inputFiles": [      "wwwroot/css/site.css"    ]  },  {    "outputFileName": "wwwroot/js/site.min.js",    "inputFiles": [      "wwwroot/js/site.js"    ],    // Optionally specify minification options    "minify": {      "enabled": true,      "renameLocals": true    },    // Optionally generate .map file    "sourceMap": false  }]

 

Two concepts are involved:

1. Bunding

It can be understood as binding or merging, that is, merging several files into a large file to reduce the number of requests.

The code above shows that inputFiles is an array, while outputFileName is a separate file name,

Taking css as an example, inputFiles already contains a file wwwroot/css/site.css. If you still need a wwwroot/css/skin.css on the page,

If the merging is not performed, the two files must be requested when the page is opened. After the merging, The skin.css file is also written to the array.

/Css/site.min.css.

2. Minification

Translate to reduce, delete comments and extra spaces in the Code, or even change the variable name to a character to reduce the file size.

For example, the following JS Code

AddAltToImg = function (imageTagAndImageID, imageContext) {    ///<signature>    ///<summary> Adds an alt tab to the image    // </summary>    //<param name="imgElement" type="String">The image selector.</param>    //<param name="ContextForImage" type="String">The image context.</param>    ///</signature>    var imageElement = $(imageTagAndImageID, imageContext);    imageElement.attr('alt', imageElement.attr('id').replace(/ID/, ''));}

Reduced code:

AddAltToImg=function(n,t){var i=$(n,t);i.attr("alt",i.attr("id").replace(/ID/,""))};

A little less.

The combination of the two methods not only reduces the number of requests, but also reduces the total size of the requested static file, thus improving the loading time and performance.

 

We have seen this code when viewing the _ layout Template File above:

 

    <environment include="Development">        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />        <link rel="stylesheet" href="~/css/site.css" />    </environment>    <environment exclude="Development">        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />    </environment>

The detailed configuration instructions are not provided for the moment. The general meaning is to load unbound and reduced files in the Development Mode for easy reading and debugging.

In non-Development cases, load processed files to improve performance.

Invalid Program. cs
    public class Program    {        public static void Main(string[] args)        {            BuildWebHost(args).Run();        }        public static IWebHost BuildWebHost(string[] args) =>            WebHost.CreateDefaultBuilder(args)                .UseStartup<Startup>()                .Build();    }

Here is a very familiar Main method, that is, the starting point of the application. After the application is started, use UseStartup <Startup> () to specify the following Startup File.

Restart Startup. cs

This is an important part of Mvc Core, including loading configurations, loading components through dependency injection, and registering routes.

In the default code:

// This method gets called by the runtime. use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder app, IHostingEnvironment env) {if (env. isDevelopment () // specifies the error page {app. useDeveloperExceptionPage ();} else {app. useExceptionHandler ("/Home/Error");} app. useStaticFiles (); // specify a static file
// Set the route app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Home}/{action = Index}/{id ?} ");});}

As shown in, two error pages in different States are set by default, static files are specified, and routes are set.

Here, we can insert the desired work content to the pipeline through middleware.

For example, we can also use app. UseAuthentication () for identity authentication.

 

We useUse,RunAndMapTo configure the HTTP pipeline.

UseMethod to short the pipe (that is, do not callnextRequest delegation ).

RunIs a convention, and some middleware components can be publicly run at the end of the PipelineRun[Middleware]Method.

Map*Extension is used as a convention to create pipeline branches.

 

There are a lot of content involved here, such as the pipeline mechanism, route registration, identity authentication, and so on all need special research.

Response. bowerrc and bower. json

Bower is an excellent front-end package and dependency management tool. bowerrc specifies the file location, and bower. json is configured in detail, as shown in the following bootstrap and jquery

{  "name": "asp.net",  "private": true,  "dependencies": {    "bootstrap": "3.3.7",    "jquery": "2.2.0",    "jquery-validation": "1.14.0",    "jquery-validation-unobtrusive": "3.2.6"  }}

The detailed usage is not described here.

 

Summary:

The structure of the newly created Project is basically like this. The main functions are described in detail.

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.