Netcore, netcore Branch
After a week, I have not shared my article, but I am mainly using it. netcore is a small project. It is almost done In addition, deletion, modification, and query targeting mass users. It is expected to be deployed on ECS this week, I also hope that you will enjoy more support after the launch. The above is purely personal nonsense. Let's take a look at the main part of today's article:
. Inherit IActionFilter to define a login verification process example
How to Use dependency injection in. ActionFilter
Let's share it one step at a time:
. Inherit IActionFilter to define a login verification process example
First, Let's define a Controller named FilterTestController and return a JsonResult. For convenience of viewing the example, we also define a class named MoResponse in this file. The corresponding code is as follows:
1 public class FilterTestController: Controller 2 {3 public JsonResult Index () 4 {5 var response = new MoResponse (); 6 response. status = 1; 7 8 return Json (response); 9} 10} 11 12 public class MoResponse13 {14 15 public int Status {get; set;} 16 public string Des {get; set ;}= "OK"; 17}View Code
Then run the command dotnet run. Enter the default port 5000 in the browser and access the defined Action. The address is http: // localhost: 5000/FilterTes, no surprise, you can see the following results:
This indicates that there is no problem in the initial construction of the project;
Next, create a class named CheckLoginAttribute and inherit and implement Attribute and IActionFilter. Here, the OnActionExecuting and OnActionExecuted methods of the IActionFilter interface are implemented, the suffix of the method name indicates that one is called after the Action is executed and the other is called after the Action method is executed. Here, most of the previous mvc versions inherit the ActionFilterAttribute, in fact, this also inherits and implements Attribute and IActionFilter, but there are other extensions, which are not detailed here:
Then we add some input information in the two OnActionExecut, and add the [CheckLogin] Mark above the Index method of FilterTestController. The Code is as follows:
Public class CheckLoginAttribute: Attribute, IActionFilter {public void OnActionExecuted (ActionExecutedContext context) {Console. writeLine (DateTime. now + "end... ");} public void OnActionExecuting (ActionExecutingContext context) {Console. writeLine (DateTime. now + "start... "); // context. result = new RedirectResult ("http://www.cnblogs.com /");}}View Code
Run the command again and access the route. You can see it in the Command form.
The OnActionExecuting in the CheckLoginAttribute corresponds to the part executed before calling the Controller Action method. The context section just commented in the code above. result = new RedirectResult ("http://www.cnblogs.com/"); is to jump to:
1. Use context. HttpContext. Session in the OnActionExecuting method to obtain the user-logged-on session (except for other session storage methods of course)
2. Use context. HttpContext. Request. Path to obtain the current access route address.
3. If the session is empty, use context. Result = new RedirectResult ("/Login? ReturnUrl = "+ context. HttpContext. Request. Path); jump to the Login route. The returnUrl parameter is used to transmit the Login information and then jump to the current access address.
How to Use dependency injection in. ActionFilter
This is a noteworthy issue, which was encountered during my initial project writing. The following are some analyses for your reference:
1. Common injection methods of netcore are injected through constructor.
2. After constructor injection, you cannot call the constructor using the corresponding number of parameters in the Action that requires Filter. You can only call the Filter constructor without parameters.
3. note that no parameter-free constructor needs to be defined in the Filter that requires dependency injection (this experiment has been done here. If TypeFilter is defined, instances will be created with no parameter constructor as the priority, this will cause dependency injection failure)
The above is the reason why the constructors cannot be directly used for dependency injection at the beginning. A useful filter, TypeFilterAttribute, was accidentally found later. The filter can be instantiated by the object passed in by the constructor, let's take a look at the following:
First, we define a MyActionFilterAttribute class and inherit TypeFilterAttribute. By default, we inherit the constructor. Then we use this custom attribute above the Controller Index and pass the CheckLoginAttribute type we define as a parameter. The following code:
[MyActionFilter (typeof (CheckLoginAttribute)] public JsonResult Index () {var response = new MoResponse (); response. Status = 1; return Json (response );}View Code
The code for MyActionFilterAttribute is as follows:
Public class MyActionFilterAttribute: TypeFilterAttribute {public MyActionFilterAttribute (Type type): base (type ){}}View Code
Well, let's customize a simple service and set the defined service to Startup. add code services to the cs file. addTransient <LogService> (); Injection service. The service requirement is to define a method. In the command box, output hello ..., the following code:
Public class LogService {public async void _ LogRequest () {await Task. run () => {for (int I = 0; I <10; I ++) {Console. writeLine (DateTime. now + "hello... ");}});}}View Code
Next, add the code in CheckLoginAttribute, for example:
1 public class CheckLoginAttribute: Attribute, IActionFilter 2 {3 private readonly LogService _ logService; 4 public CheckLoginAttribute (LogService logService) 5 {6 7 _ logService = logService; 8} 9 10 public void OnActionExecuted (ActionExecutedContext context) 11 {12 13 Console. writeLine (DateTime. now + "end... "); 14} 15 16 public void OnActionExecuting (ActionExecutingContext context) 17 {18 19 Cons Ole. writeLine (DateTime. now + "start... "); 20 21 var path = context. httpContext. request. path; 22 // context. result = new RedirectResult ($ "/Login? ReturnUrl = {path} "); 23 24 _ logService. _ LogRequest (); 25} 26}View Code
Well, what we can see in dotnet run together is:
This dependency is successfully injected into the Filter. In fact, the MyActionFilterAttribute defined above can also be seen as redundant, because the constructors of TypeFilterAttribute are actually used in the Action, how can we directly use TypeFilter on Action?
The two have the same effect, but define a Filter that can record other log information or do other things. This is the content shared this time. I don't know whether the description is clear, thank you for your support.