NET Core-learning notes (2), netcore-learning notes
Here we will share with you the previous article: NET Core-learning notes (1) continue to learn core notes. If you have any problems or better insights, I hope you can share them more.
The following are the learning steps to be shared in this article. I will share with you some of my new or coming soon:
1. Read the Controller code automatically generated by the core framework.
2. Restrictions on the format of routes and route Parameters
3. Two methods to set the virtual path to access the resource folder and the effect difference
4. How to set global response information for abnormal access?
5. constructor dependency injection method ILogger, IOptions example
6. Use ConfigurationBuilder
Let's share it one step at a time:
1. Read the Controller code automatically generated by the core framework.
First, let's look at a picture.
The highlighted part is already in the red box. The data context of the ApplicationDbContext application is passed by the constructor. However, in this case, the corresponding class of the new constructor is usually required, can be passed into the parameter. When the entire project does not find the corresponding location of the new Controller, this also extends the injection method mentioned here; you can open the project file Startup for this ApplicationDbContext. cs contains the following section:
1 services. AddDbContext <ApplicationDbContext> (options => options. UseSqlServer (Configuration. GetConnectionString ("DefaultConnection ")));View Code
Yes, the context for accessing the database is injected here. You only need to connect to the database in this section. getConnectionString is the string used to obtain the database. The previous articles briefly describe it;
Secondly, we can see that several operations in the Controller are in the async Task mode, and the corresponding methods use await FunAsync (); to return data, we should be familiar with the several keywords here, which are extended by the 4.5 framework. To put it simply, the logic that I pay attention to when using these keywords is that async await must be paired, await can also be seen from the word as the meaning of waiting, mainly waiting for the subsequent method execution to complete the returned results. The returned results correspond to the data packaged by the Task, and the Task has the Result, in this way, the Result of the previous method is obtained through Result;
2. Restrictions on the format of routes and route Parameters
First, mvc has to say that the corresponding route core framework sets the route in the Configure method of the StartUp. cs file. The initialization code is as follows:
1 // set mvc routing 2 app. UseMvc (routes => 3 {4 // here's {id ?} ? Number indicates that there can be a routes. MapRoute (6 name: "default", 7 template: "{controller = Home}/{action = Index}/{id ?} "); 8 });View Code
There are two ways to set the default value: one is to set the default value directly after the = sign as in the above Code, the third parameter of the MapRoute method is in the same format as the previous mvc version new {param}. You can try it by yourself;
Then, we set a parameter format limit directly after the parameter: Data Type (such as id: int). At this time, the parameter can only pass the corresponding data type, here we will list two formats (if the regular expression is not required, remove \):
1 routes. mapRoute (2 name: "first", 3 template: "{controller = Home}/{action = Index}/{id: int}"); 4 routes. mapRoute (5 name: "second", 6 template: "{controller = Home}/{action = Index}/{id: regex (d + )}");View Code
Very practical more limits can be viewed: https://docs.asp.net/en/latest/fundamentals/routing.html
3. Two methods to set the virtual path to access the resource folder and the effect difference
First, locate Startup. the Configure method of the cs file. To open the directory for viewing accessible resources, you need to use the UseDirectoryBrowser and UseFileServer methods. In fact, they all correspond to the AddDirectoryBrowser () service added in the ConfigureServices service method, therefore, you need to add services in the ConfigureServices service method. addDirectoryBrowser (); Code;
Let's take a look at the UseDirectoryBrowser method. Let's create an angularjs folder in the core project and directory together and add the angular-1.0.js file in it, file content can be arbitrary (I only have a note here // here is ng), directory results
Then add the following code in the Configure method:
1 public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 2 {3 4 // start disk view 5 app. useDirectoryBrowser (new DirectoryBrowserOptions 6 {7 FileProvider = new PhysicalFileProvider (Path. combine (Directory. getCurrentDirectory (), "angularjs"), 8 RequestPath = "/ng" 9 10}); 11}View Code
PhysicalFileProvider corresponding to FileProvider is mainly used to set the physical path. RequestPath corresponds to the virtual path, that is, the path open to the browser for resource access. The browser effect after executing the dotnet run Command is as follows:
The effect here is that you can click the js file, but you cannot directly display the content of the js file in the browser, that is, you cannot access the js file;
Let's take a look at UseFileServer (). Let's comment out the UseDirectoryBrowser code to avoid affecting the effect, and then add the following code in the Configure method:
1 public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 2 {3 app. useFileServer (new FileServerOptions () 4 {5 FileProvider = new PhysicalFileProvider (6 Path. combine (Directory. getCurrentDirectory (), "angularjs"), 7 RequestPath = "/ng1", 8 EnableDirectoryBrowsing = true 9}); 10}View Code
Note that the name of the virtual path is ng1, and an EnableDirectoryBrowsing = true is added, which means that the effect of allowing disk browsing is equivalent to the added code services. addDirectoryBrowser () is used to browse the file directory without the need for this statement. The effect is as follows:
You can also view the directory structure here, and click the js file to view it in the browser:
Yes, this is the content of the js file. This method can directly download a file, but the first one won't work. If you want the first method to download or view the js file, you can use UseStaticFiles () to set the parameters. The Code is as follows:
1 app. useStaticFiles (new StaticFileOptions 2 {3 4 FileProvider = new PhysicalFileProvider (Path. combine (Directory. getCurrentDirectory (), "angularjs"), // physical root path 5 RequestPath = "/ng" // set the virtual access path 6 7 }); 8 9 // start the disk file to view 10 apps. useDirectoryBrowser (new DirectoryBrowserOptions11 {12 FileProvider = new PhysicalFileProvider (Path. combine (Directory. getCurrentDirectory (), "angularjs"), 13 RequestPath = "/ng" 14 15 });View Code
Note that the parameters RequestPath corresponding to the two methods are "/ng". The purpose is to set these two virtual paths to the same. The UseStaticFiles () method function is to run a directory where files are accessed, the default value is. the automatically generated code of netcore contains an app. useStaticFiles (); by default, only static Resources in the wwwroot folder of the project can be accessed. To access static resources in other root directories, you can set the above Code, note that the custom resource access settings must be in the default code app. useStaticFiles (); otherwise, the built-in static files cannot be used.
4. How to set global response information for abnormal access?
The method to be introduced here is also executed in the Configure method, the UseStatusCodePages () and UseExceptionHandler () functions. Currently, only the UseStatusCodePages parameter settings are tested, I hope my friends can tell me the results and application scenarios after the test. Thank you;
First, the app. useStatusCodePages ("text/plain", "this is the status code returned by response: {0}"); here I directly return text data to the page, the result is that an address not included in the route is entered in the browser, so the browser will display this information. Note {0} here. You can refer to the method remarks, the description indicates that the placeholder is directly used to indicate the Status code returned by Response. If I access an address that is no longer in the route here, the effect is as follows:
Then, the app. useExceptionHandler ("/Home/Error"); this is the default code for creating a project. The route pointing here is the Error method in HomeController, and the corresponding attempt is not found, I don't know whether the project does not need it or what it looks like. If you know it, let me know;
5. Example of constructor dependency Injection
The constructor dependency injection has been mentioned earlier, that is, in ApplicationDbContext and the first shared code, here we are talking about the ILogger (Log Service) that comes with the other two netcore projects) and IOptions <T> (option to access the service), directly add the Code:
1 public class ArticlesController: Controller 2 {3 private readonly ApplicationDbContext _ context; 4 5 private readonly IOptions <Article> _ opArticle; 6 7 private readonly ILogger <ArticlesController> _ log; 8 9 10 public ArticlesController (ApplicationDbContext context, IOptions <Article> opArticle, ILogger <ArticlesController> log) 11 {12 _ context = context; 13 _ opArticle = opArticle; 14 _ log = log; 15} 16 17 // GET: Articles18 public async Task <IActionResult> Index () 19 {20 _ log. logInformation ("I {0} {1}", "love", "zuguo"); 21 ViewBag. TResult = 4 + 5; 22 ViewBag. touTiao = _ opArticle. value. title; 23 24 return View (await _ context. article. toListAsync (); 25} 26}View Code
Here ILogger <T> assigns a value to the read-only Variable _ log through the constructor. Because it is dependent on injection, you can directly use the method. Here I use one of the reloads of the LogInformation method, the result is that the cmd command window displays the Info level information when accessing the Controller Index:
For more level information, see: https://docs.asp.net/en/latest/fundamentals/logging.html
Relatively speaking, when using IOptions <T>, You need to manually start up. the ConfigureServices method in the cs file sets the code services. addOptions () to add a service. This option can access the service function to inject the class that meets its generic needs, and the class of new () to other places, here is an example of adding the following code in the ConfigureServices method:
1 services. addOptions (); 2 // initialize parameter information 3 services. configure <Models. aiticleModels. article> (B => 4 {5 6 B. title = "toutiao, patriotic activities"; 7 });View Code
Then, you can get the parameter value somewhere injected by the constructor. You only need to inject the object. value to get the injected generic T instance. The corresponding code is the code starting from. effect:
6. Use ConfigurationBuilder
The following code is automatically generated by the framework:
1 public Startup (IHostingEnvironment env) 2 {3 // here, the ConfigurationBuilder is created to load configuration files such as Congfig 4 var builder = new ConfigurationBuilder () 5 6 // env. contentRootPath: Get the path of the current project. setBasePath (env. contentRootPath) 8 // use the AddJsonFile method to restore the metadata of the project. the json configuration file is loaded in. The reloadOnChange is called reloadOnChange. addJsonFile ("deleteworkflow. json ", optional: true, reloadOnChange: true) 10 // here we are concerned with $" {param} ", which is a bit similar to string. format () 11. addJsonFile ($ "deleettings. {env. environmentName }. json ", optional: true); 12 13 if (env. isDevelopment () 14 {15 // 16 builder to be studied. addUserSecrets (); 17 18 // to be studied 19 builder. addApplicationInsightsSettings (valid mode: true); 20} 21 22 builder. addEnvironmentVariables (); 23 24 // This returns a Configuration file and node: IConfigurationRoot25 Configuration = builder. build (); 26 27}View Code
This ConfigurationBuilder reads the configuration file when loading it in the starter Startup (for more information, see the first article or code comment). Here we use the AddInMemoryCollection method to increase the data of the configuration file instance:
// Add configuration data builder. AddInMemoryCollection (new Dictionary <string, string >{{ "home", "zuguo "}});View Code
After that, we can get the value in the Configuration. Here we use
Var home = Configuration ["home"];
Console. WriteLine ($ "hello, {home }");
The following information is displayed in the Command window:
This article is here, I hope it will bring you benefits, and I hope you will have more experiences.