NET Core-learning notes (3), netcore-learning notes

Source: Internet
Author: User

NET Core-learning notes (3), netcore-learning notes

Here we will share with you the third part of the study summary. First of all, I would like to express my feelings about some problems I encountered when I followed the netcore official website this week:

A. the nuget package used in the English version of the official website is inconsistent with the latest package version I installed at the time, so I cannot follow the example of the column test given in the textbook. The latest package has not been released yet.

B. Some materials are not detailed enough, just a single sentence. When the network speed is slow, I cannot check the information.

Well, after feeling it, the following is the learning step to be shared in this article. Let's talk to each other about new or coming soon:

 

1. Model Validation (entity Model verification)

2. Custom verification attributes

3. Create an interface that supports returning json and xml data formats

 

Let's share it one step at a time:

1. Model Validation (entity Model verification)

Entity model verification: You can directly add annotations to define the format to be verified. To use annotations, you must reference the namespace System. ComponentModel. DataAnnotations in the object class file as follows:

The content in the red box is the usage. It is enclosed in brackets ('[]') above the attribute field. The Braces ('()') are passed parameters. Here Required is used: required, StringLength (100): the minimum length of input characters is 100, ClasssicMoive (1960): Custom verification, DataType (DataType. date): the attribute is in the Date format. There are also many common verification features. You can go to this address: https://docs.asp.net/en/latest/mvc/models/validation.html;

Here we will focus on the two:

Remote (using Remote verification): In general, the specified route is used to verify whether the value of this attribute is valid on the backend. It is a server verification; the instance usage of the method is as follows (here is a usage, you can try to reload the method ):

Here, the required parameter is routeName, which is the route. Some of the following attributes are not required.

First, define a route to verify whether it contains Blogs. The Code is as follows:

1 [AcceptVerbs ("Get", "Post")] 2 public JsonResult IsContainerBlogs (string title) 3 {4 5 if (! Title. Contains ("Blogs") | string. IsNullOrEmpty (title) 6 {7 8 return Json ("there is no Blogs in the Title! "); 9} 10 return Json (true); 11}View Code

The AcceptVerbs feature is mainly used to restrict only get and post requests.

Then, define an article entity in the following format:

1 public class Article2 {3 [Required] 4 public int ID {get; set;} 5 6 [Remote (action: "IsContainerBlogs", controller: "ArticlesFormat")] 7 public string Title {get; set;} 8 public DateTime CreateTime {get; set;} 9}View Code

And automatically generate the corresponding View and Controller (Here we mainly demonstrate the remote effect. For details about how to generate the view and Controller, refer to the previous article: NET Core-learning notes (1 )), let's start the dotnet run Command to access the page for creating an article. First, let's look at the html code generated by the Title attribute:

Some paths in the red box are the routing of the Action and Controller specified in the object. Let's take a look at the effect:

If there is no Blogs, the system will prompt the error message returned by the routing definition method,

 

The Title results with Blogs are successfully added,

 

 

RegularExpression (Regular Expression verification): verifies the data validity according to the custom RegExp rule;

Use the Title as an example, comment out the previous Remote, and replace it with RegularExpression. The Code is as follows: [RegularExpression (pattern: "d +", ErrorMessage = "do not comply with regular Rules")], the Title content is limited to numbers. The test result is as follows:

 

2. Custom verification attributes

To implement custom model verification, you must inherit: System. ComponentModel. DataAnnotations. ValidationAttribute. The code is displayed here. For more details, see create a ModelRegexExtendAttribute class in the code comment to inherit ValidationAttribute:

1 public class ModelRegexExtendAttribute: ValidationAttribute 2 {3 private string _ pattern; 4 public ModelRegexExtendAttribute (string pattern = @ "\ d +", string errorMessage = "must meet regular ") 5 {6 _ pattern = pattern; 7 this. errorMessage = errorMessage; 8} 9 10 11 protected override ValidationResult IsValid (object value, ValidationContext validationContext) 12 {13 // validationContext. displayName: Specify the attributes of an object class 14 // obtain the attributes related to the specified attribute 15 var t = validationContext. objectType. getProperty (validationContext. displayName); 16 // obtain the value of the corresponding attribute 17 var p = t. getValue (validationContext. objectInstance, null); 18 19 // do the regular expression for 20 if (Regex. isMatch (p. toString (). toUpper (), _ pattern) 21 {22 23 return ValidationResult. success; 24} 25 26 return new ValidationResult (this. errorMessage); 27} 28 29}View Code

This custom verification is the same as the above verification:

Run dotnet run again, and then refresh the page for adding text just now. The verification operation is the same as the above.

 

3. Create an interface that supports returning json and xml data formats

First, create a Controller named ArticlesFormatController (actually the Controller mentioned in the second point), and then inject ApplicationDbContext to access the list data of the article (here you can take a look at the study notes (1) ). The specific implementation methods of ArticlesFormatController include:

1 public class ArticlesFormatController: Controller 2 {3 4 private readonly ApplicationDbContext _ context; 5 6 public ArticlesFormatController (ApplicationDbContext context) 7 {8 9 _ context = context; 10} 11 12 [Route ("[controller]/[action]")] 13 public async Task <List <Article> GetArticles () 14 {15 16 return await _ context. article. toListAsync (); 17} 18 19 20 // [Route ("[controller]/[action]/{id }. {Mat ?} ")] 21 public async Task <Article> GetArticle (int? Id) 22 {23 24 if (id = null) 25 {26 27 return new Article (); 28} 29 return await _ context. article. where (B => B. ID = id ). singleOrDefaultAsync (); 30} 31 32 public string GetArticleName (int? Id) 33 {34 if (id = null) 35 {36 37 return string. empty; 38} 39 return _ context. article. where (B => B. ID = id ). singleOrDefaultAsync (). result. title; 40} 41 42 43 [AcceptVerbs ("Get", "Post")] 44 public JsonResult IsContainerBlogs (string title) 45 {46 47 if (! Title. Contains ("Blogs") | string. IsNullOrEmpty (title) 48 {49 50 return Json ("the Title does not contain Blogs! "); 51} 52 return Json (true); 53} 54 55}View Code

In this case, access the article list in the browser through the route: http: // localhost: 5000/ArticlesFormat/GetArticles to obtain the following information:

In this case, the defined Controller returns json data, which is the json data returned by the framework by default;

Next, in the ConfigureServices service method of the Startup. cs file, find the default generated services. AddMvc () code, and convert it to this:

1 services. AddMvc (op => 2 {3 4 op. OutputFormatters. Add (new XmlSerializerOutputFormatter (); 5}). AddXmlSerializerFormatters ();View Code

An error will be reported when the code is generated. If you cannot find a package, you must use nuget to add Microsoft. AspNetCore. Mvc. Formatters. Xml to the project:

OK. Now, you can directly reference a space in "Startup. cs": using Microsoft. AspNetCore. Mvc. Formatters, and then generate the next project. Is this a compilation error;

Then, dotnet run runs the startup project again, and the browser directly accesses the json data from http: // localhost: 5000/ArticlesFormat/GetArticles, Which is disappointing, however, generally, the Accept type of the receiving property type is specified in the interface form. In this case, try using the DHCgoogle plug-in (which is actually a post or get access tool );

First, a json data:

If it is a little too big, Do not spray it. Let's return another xml data:

 

The final figure is a little long. I hope the reviewers will not care about it. Here, we will return the json and xml format data. You can try it and share it here today. Thank you.

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.