After a week of not sharing the article, Mainly in the use of. Netcore do a small project, the project for the public users of the deletion and modification of the changes are almost done, intends to deploy in the cloud server this week to try, very look forward to, but also hope that after the launch of a lot of support; The above is purely personal nonsense, to take a look at today's positive article link:
. Inherit iactionfilter to define a process example of authentication login
. How to use dependency injection in Actionfilter
The following step by step to share:
. Inherit iactionfilter to define a process example of authentication login
First, we define a controller named Filtertestcontroller, which returns a jsonresult result; for example, for the convenience of viewing, and in this file define a class named Moresponse, the corresponding code is as follows:
1 Public classFiltertestcontroller:controller2 {3 Publicjsonresult Index ()4 {5 varResponse =Newmoresponse ();6Response. Status =1;7 8 returnJson (response);9 }Ten } One A Public classMoresponse - { - the Public intStatus {Get;Set; } - Public stringDes {Get;Set; } ="Ok"; -}
View Code
Then, execute the Run command dotnet run, enter the default port in the browser good 5000 and access the action just defined, address such as: http://localhost:5000/FilterTes, no accident everyone can see the following results of the pattern:
This indicates that the project was initially built with no problems;
Next, create a class named Checkloginattribute and inherit and implement attribute, Iactionfilter, where the onactionexecuting of the Iactionfilter interface is implemented, OnActionExecuted two methods, look at the method name suffix probably understand that one is the action execution, one is called after the action method executes, here is a simple addition to the previous version of MVC is mostly to inherit ActionFilterAttribute , in fact, this also to inherit and realize the attribute, Iactionfilter, but there are other extensions just, here is not detailed to distinguish the description:
Then we add some input information to the two onactionexecut, and add the [Checklogin] tag above the Filtertestcontroller index method, with the following code:
Public classCheckloginattribute:attribute, Iactionfilter { Public voidonactionexecuted (ActionExecutedContext context) {Console.WriteLine (DateTime.Now+"End ..."); } Public voidonactionexecuting (ActionExecutingContext context) {Console.WriteLine (DateTime.Now+"start ..."); //context. Result = new Redirectresult ("http://www.cnblogs.com/"); } }
View Code
Run again, access the route you just made, and you can see it in the command form
The onactionexecuting in Checkloginattribute just now corresponds to the part that was executed before the action method of the controller was called, and the above code just commented on the part of the context. Result = new Redirectresult ("http://www.cnblogs.com/") is a jump to the http://www.cnblogs.com/address, if the comment is released, See the effect is to access before controller route directly to the address, and the fame form only start ... section of the log, without the previous end ... section, you can see the context here. The result effect is the direct termination of the program to continue execution; here we go. A simple login verification, I just say the process, do not do specific code, because this is not the focus haha:
1. Use Context.HttpContext.Session in the OnActionExecuting method to get the user's login session (except, of course, other session save methods)
2. Use the context. HttpContext.Request.Path get the routing address of the current access
3. If the session is empty, use the context. Result = new Redirectresult ("/login?returnurl=" + context.) HttpContext.Request.Path); Jump to the route login, ReturnUrl parameter use to pass the login and then jump to the current access address
. How to use dependency injection in Actionfilter
This is the place to be concerned, this is the problem that I encountered when my project was first written, and here are some analyses that you can refer to:
The 1.netcore common injection method is injected through the constructor function.
2. After the constructor is injected, it is not possible to call the constructor with the number of corresponding arguments in the action that requires the filter; only the filter constructor with no parameters
3. Note that there is no need to define an parameterless constructor in a filter that requires dependency injection (this is done experimentally, if the definition typefilter will create an instance with the parameterless constructor as a priority, it will be a dependency injection failure)
The above is the first reason why you cannot directly use a struct dependency injection, and later inadvertently found a very useful filter: Typefilterattribute, the filter can be passed in through the constructor of the object instantiation, let's look at the following:
First, we define a Myactionfilterattribute class and inherit Typefilterattribute, the default inheritance constructor, Then use this custom attribute above the controller's index and pass our defined Checkloginattribute type as a parameter, as in the following code:
[Myactionfilter (typeof(Checkloginattribute))] Public jsonresult Index () { varnew moresponse (); 1 ; return Json (response); }
View Code
The Myactionfilterattribute code is as follows:
Public class Myactionfilterattribute:typefilterattribute { publicbase(type) { } }
View Code
Well, let's customize a simple service and add code services.addtransient<logservice> () to the Startup.cs file for the defined service, and the service requirement is to define a method, In the command box, output hello ... with the following code:
public class Logservice { public async void _logrequest () { await Task.run (() => { for (int i = 0 ; i < 10 ; I++ + " hello ... " ); } }); } }
View Code
Again, add code in the Checkloginattribute such as:
1 Public classCheckloginattribute:attribute, Iactionfilter2 {3 Private ReadOnlyLogservice _logservice;4 PublicCheckloginattribute (logservice logservice)5 {6 7_logservice =Logservice;8 }9 Ten Public voidonactionexecuted (actionexecutedcontext context) One { A -Console.WriteLine (DateTime.Now +"End ..."); - } the - Public voidonactionexecuting (actionexecutingcontext context) - { - +Console.WriteLine (DateTime.Now +"start ..."); - + varPath =context. HttpContext.Request.Path; A //context. Result = new Redirectresult ($ "/login?returnurl={path}"); at - _logservice._logrequest (); - } -}
View Code
All right, let's go. dotnet run See effects such as:
This dependency is injected into the filter to succeed, in fact, the definition of the Myactionfilterattribute can also be considered redundant, because the action is actually used in the Typefilterattribute own constructor method, We can use TypeFilter directly on the action
The effect is the same, just define a filter can record other log information or do other things, this share of the content is this, do not know whether the description is clear, I hope a lot of support, thank you.
The use of NETCORE-MVC's Actionfilter