Component writing in Asp. NetCore and asp. netcore

Source: Internet
Author: User

Component writing in Asp. NetCore and asp. netcore

This chapter is about Asp. netCore component writing method. In netcore, many things are used by providing components, such as MVC Architecture, Session, Cache, and database reference; here, I also call the verification code interface to customize a component to illustrate how to use it and the scenarios that need attention during use;

Hello world of Middleware

For netcore, components are usually referenced in the Startup class corresponding to UseStartup <Startup>. The Startup class can be changed to its own custom actual class, but it needs to be pointed to when UseStartup; here we take the Startup class as an example. Through the files automatically generated by vs, we can see in this class that the Configure method body contains: app. useMvc (), app. useStaticFiles (), app. xxx () and some other components included in the column. Let's take a look at the custom hello world component instance. First, use the static Extension Method to expandIApplicationBuilder:

1 public static class MiddlewareExtends 2 {3 /// <summary> 4 /// test case middleware 5 /// </summary> 6 /// <param name = "builder"> </param> 7 // <returns> </returns> 8 public static IApplicationBuilder UseTest (this IApplicationBuilder builder) 9 {10 return builder. useMiddleware <TestMiddleware> (); 11} 12 13}

Use builder. UseMiddleware <TestMiddleware> () to add custom components. The component implementation code is as follows:

1 public class defaults 2 {3 private RequestDelegate _ requestDelegate; 4 public TestMiddleware (RequestDelegate requestDelegate) 5 {6 _ requestDelegate = requestDelegate; 7} 8 9 public Task Invoke (HttpContext context) 10 {11 12 context. items ["TestMiddleware"] = "hello world, I'm TestMiddleware. "; 13 14 return _ requestDelegate (context); 15} 16}

The above is the most basic component format. Note:

1. The component must have a public Task Invoke (HttpContext context). HttpContext is the http context, and the Invoke () delegate method enters the Invoke every time the program is accessed;

2. public delegate Task RequestDelegate (HttpContext context) must be available; delegate methods to respond to http requests;

At this point, hello world is complete. To test the method, we directly write the following code in the action:

1  public IActionResult About()2         {3 4             ViewData["Message"] = HttpContext.Items["TestMiddleware"];5             return View();6         }

Running result:

 

Asynchronous component writing
1 public class interval 2 {3 private RequestDelegate _ requestDelegate; 4 public TestMiddleware (RequestDelegate requestDelegate) 5 {6 _ requestDelegate = requestDelegate; 7} 8 9 public async Task Invoke) 10 {11 12 context. items ["TestMiddleware"] = "hello world, I am asyncTestMiddleware. "; 13 14 await _ requestDelegate (context); 15} 16}

You only need to combine async and await;

 

. Netcore custom Verification Code component
1 /// <summary> 2 // text Verification Code 3 /// </summary> 4 public class WenZiCodeMiddleware 5 {6 private RequestDelegate _ requestDelegate; 7 public WenZiCodeMiddleware (RequestDelegate requestDelegate) 8 {9 _ requestDelegate = requestDelegate; 10} 11 12 public async Task Invoke (HttpContext context) 13 {14 15 var url =" http://localhost:1001/shenniuapi/WenZiValidateCode "; 16 using (HttpClient client = new HttpClient () 17 {18 client. timeout = TimeSpan. fromSeconds (60); 19 20 var str = "{\" UserName \ ": \" shiniu walk 3 \ ", \" UserPwd \ ": \" 4297f44b13955235245b2497399d7a93 \", \ "Token \": \ "008 I'm a test \"} "; 21 var content = new StringContent (str, Encoding. UTF8, "application/x-www-form-urlencoded"); 22 content. headers. contentType = new MediaTypeHeaderValue ("application/json"); 23 var result01 = client. postAsync (url, content ). result; 24 var stream = await result01.Content. readAsStreamAsync (); 25 using (var reader = new StreamReader (stream) 26 {27 var result02 = await reader. readToEndAsync (); 28 context. items ["codedata"] = result02; 29} 30} 31 32 await _ requestDelegate (context); 33} 34}

We also need to add the following code to the static Extension Method to add components:

1 /// <summary> 2 // text Verification Code middleware 3 /// </summary> 4 /// <param name = "builder"> </param> 5/ // <returns> </returns> 6 public static IApplicationBuilder UseWenZiValidateCode (this IApplicationBuilder builder) 7 {8 return builder. useMiddleware <WenZiCodeMiddleware> (); 9}

In the Configure method, reference the component: app. UseWenZiValidateCode (); Action, use the component:

1  public FileResult GetCode()2         {3             var data = HttpContext.Items["codedata"].ToString();4             var code = JsonConvert.DeserializeObject<MoValidateCodeResponse>(data);5             return File(code.CodeStream, "image/jpeg");6         }

Code in View attempt:

1 GetCode:

Effect display:

Here, we need to consider the scenario that the Invoke method we mentioned above will access any request. Isn't it reasonable to make the verification code component, because the verification code is only needed on the login interface or verification interface. For example, the verification code component we wrote above will be executed by the program every time. This is obviously unreasonable, therefore, I personally think that if you need custom components, you need to consider: whether each request needs to enter your component service. If you do not need them, there is no need to create a component, of course it feels very high; so here I have to use the static Extension Method (of course there are other ways) to override the method for obtaining the verification code;

 

Static Extension Method rewrite Verification Code component

Since we have a static class when adding components above, we add the extension method directly above:

1 // <summary> 2 // text Verification Code 3 /// </summary> 4 /// <param name = "context"> </param> 5 // /<returns> </returns> 6 public static async Task <MoValidateCodeResponse> WenZiCode (this HttpContext context) 7 {8 var code = default (MoValidateCodeResponse); 9 try10 {11 var url =" http://localhost:1001/shenniuapi/WenZiValidateCode "; 12 using (HttpClient client = new HttpClient () 13 {14 client. timeout = TimeSpan. fromSeconds (60); 15 16 var str = "{\" UserName \ ": \" shiniu walking 3 \ ", \" UserPwd \ ": \" 4297f44b13955235245b2497399d7a93 \", \ "Token \": \ "008 I'm a test \"} "; 17 var content = new StringContent (str, Encoding. UTF8, "application/x-www-form-urlencoded"); 18 content. headers. contentType = new MediaTypeHeaderValue ("application/json"); 19 var result01 = client. postAsync (url, content ). result; 20 var stream = await result01.Content. readAsStreamAsync (); 21 using (var reader = new StreamReader (stream) 22 {23 var result02 = await reader. readToEndAsync (); 24 code = await JsonConvert. deserializeObjectAsync <MoValidateCodeResponse> (result02); 25} 26} 27} 28 catch (Exception ex) 29 {30} 31 return code; 32}

Corresponding verification code entity class:

1 /// <summary> 2 // The shenniu interface returns the base class 3 /// </summary> 4 public class MoShenNiuBaseResponse 5 {6 // <summary> 7 // /return status: 0: Failed 1: Successful 8 // </summary> 9 public int Status {get; set ;} 10 11 /// <summary> 12 // error message 13 /// </summary> 14 public string Msg {get; set ;} 15} 16 17 /// <summary> 18 // Verification Code return class 19 /// </summary> 20 public class MoValidateCodeResponse: MoShenNiuBaseResponse21 {22 23 public MoValidateCodeResponse () 24 {25 this. imgCode = new List <MoImgCode> (); 26} 27 28 /// <summary> 29 // verification Code type 30 /// </summary> 31 public string Code {get; set ;} 32 33 // <summary> 34 // Verification Code image stream 35 /// </summary> 36 public byte [] CodeStream {get; set ;} 37 38 // <summary> 39 // image verification coordinate 40 /// </summary> 41 public List <MoImgCode> ImgCode; 42} 43 44 // <summary> 45 // image Verification Code coordinate 46 // </summary> 47 public class MoImgCode48 {49 public string Index {get; set ;} 50 51 public string IndexType {get; set;} 52 53 public string ImgUrl {get; set;} 54 55 public Point Point_A {get; set ;} 56 57 public Point Point_ B {get; set;} 58 59 public bool IsChoice {get; set;} 60} 61 62 public class Point63 {64 public int X {get; set ;} 65 public int Y {get; set;} 66}View Code

At this time, it also comes to Action:

1  public async Task<FileResult> GetCodeAsync()2         {3             var code = await HttpContext.WenZiCode();4 5             return File(code.CodeStream, "image/jpeg");6         }

Modify the view attempt code and click the verification code image to obtain the new verification code:

 1 <style type="text/css"> 2     img{cursor:pointer} 3 </style> 4 

:

The above is all the content in this article, aiming to share how to write a component and when to use the component. Thank you for your support and thumbs up.

 

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.