In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to use ActionFilter in asp.net core. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
1. ActionFilter introduction
The full name of ActionFilter is ActionFilterAttribute. According to Microsoft's naming convention, we can see that this is a feature class. Take a look at its declaration:
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
Public abstract class ActionFilterAttribute: Attribute, IActionFilter, IFilterMetadata, IAsyncActionFilter, IAsyncResultFilter, IOrderedFilter, IResultFilter
This is a property class that allows tagging on classes and methods, allowing multiple tags, after which the subclass inherits the properties of the parent class. Then, this class is an abstract class, so we can write our own ActionFilter by inheriting from ActionFilterAttribute.
1.1 four methods of ActionFilter
The most important thing for an ActionFilter is its four methods:
Public virtual void OnActionExecuted (ActionExecutedContext context)
Public virtual void OnActionExecuting (ActionExecutingContext context)
Public virtual void OnResultExecuted (ResultExecutedContext context)
Public virtual void OnResultExecuting (ResultExecutingContext context)
The figure above shows the order in which these four methods are executed in a single request. To intercept a request before it is actually executed, you should use OnActionExecuting.
Why do you say this alone? Because of the high appearance rate of this method, this method is used for request filtering most of the time.
1.2 what can we do in ActionFilter
Let's briefly introduce the four context types of the four methods and take a look at what we can take advantage of:
1.2.1 ActionExecutingContext
This is a context before Action execution, indicating that Action has not started execution, but the controller instance has been obtained:
Public class ActionExecutingContext: FilterContext
{
Public virtual IDictionary ActionArguments {get;}
Public virtual object Controller {get;}
Public virtual IActionResult Result {get; set;}
}
ActionExecutingContext inherits from FilterContext, so let's just ignore its parent class and just look at its own properties.
ActionArguments represents the parameter list of Action, which contains various parameters received from the user and other parameters added by intermediate handlers
Controller represents the controller that executed the request. As we mentioned earlier, asp.net core has very few restrictions on the controller, so any type of controller is possible, so here we use object as the controller type.
Result executes the result, and normally it doesn't make sense to get the value of this property here. But we can intercept requests by changing the value of this property
1.2.2 ActionExecutedContext
ActionExecutedContext represents the context after the Action execution is completed. By this time, the Action execution has been completed, and we can obtain the Action execution result through this:
Public class ActionExecutedContext: FilterContext
{
Public virtual bool Canceled {get; set;}
Public virtual object Controller {get;}
Public virtual Exception Exception {get; set;}
Public virtual ExceptionDispatchInfo ExceptionDispatchInfo {get; set;}
Public virtual bool ExceptionHandled {get; set;}
Public virtual IActionResult Result {get; set;}
}
Again, inherit from FilterContext and ignore it for the time being.
Canceled indicates whether the short circuit is set.
Controller on which the Controller processes the request
Whether an exception occurs during the execution of Exception. If there is an exception, there is a value, otherwise it is Null
Whether the ExceptionHandled exception is handled
Result modifying the Result here does not mask the executed ActionResult, but the corresponding implementation can be hidden from the user
1.2.3 ResultExecutingContext
This is the context of execution before Result rendering, when Action has finished executing and is ready to render Result:
Public class ResultExecutingContext: FilterContext
{
Public virtual bool Cancel {get; set;}
Public virtual object Controller {get;}
Public virtual IActionResult Result {get; set;}
}
Cancel cancels the execution of the current result and subsequent filters
Controller controller
Result processing result
1.2.4 ResultExecutedContext
Result has been executed. Get the context of the execution result:
Public class ResultExecutedContext: FilterContext
{
Public virtual bool Canceled {get; set;}
Public virtual object Controller {get;}
Public virtual Exception Exception {get; set;}
Public virtual ExceptionDispatchInfo ExceptionDispatchInfo {get; set;}
Public virtual bool ExceptionHandled {get; set;}
Public virtual IActionResult Result {get;}
}
This class is similar to ActionExecutedContext and will not be introduced.
1.2.5 FilterContext
The above four contexts all inherit from FilterContext, so let's take a look at what properties or methods are in FilterContext:
Public abstract class FilterContext: ActionContext
{
Public virtual IList Filters {get;}
Public TMetadata FindEffectivePolicy () where TMetadata: IFilterMetadata
}
You can see that FilterContext inherits another ActionContext's class. Friends should have some idea of this class, which is the context class of Action. It exists completely in the life cycle of an Action, so sometimes Action-level data transfer can be done through ActionContext (not recommended).
So, let's go back and see what's in ActionContext:
Public class ActionContext
{
Public ActionDescriptor ActionDescriptor {get; set;}
Public HttpContext HttpContext {get; set;}
Public ModelStateDictionary ModelState {get;}
Public RouteData RouteData {get; set;}
}
The Action description information executed by ActionDescriptor, including the display name of Action, some parameters, etc. When used, it will be explained in detail for everyone.
HttpContext can obtain the Request and Response objects of this request through this property.
ModelState model verification information, this part will be explained in detail for friends later.
RouteData routing information, the routing information parsed by asp.net core when processing the request, including the routing information modified in the program
two。 Use ActionFilter
In the previous article, "[asp.net core Series] 9 practical UnitOfWork and Custom Code Generation," it was introduced that ActionFilter is consistent with the general feature class, and the ActionFilter can be enabled by tagging the controller.
Because in most cases, an ActionFilter will not be limited to one controller, but will be applied to multiple controllers. So at this point, we usually set up a base controller, mark it on it, and then let the subclass inherit the controller. This is the way to implement multiple uses of a declaration.
Of course, another way to use ActionFilter has been added to asp.net core, in Setup.cs
Public void ConfigureServices (IServiceCollection services)
{
Services.AddControllersWithViews ()
}
By default, we can add a globally applied Filter by setting parameters, such as the UnitOfWorkFilterAttribute we created in the previous article:
Services.AddControllersWithViews (options= >
{
Options.Filters.Add ()
});
A global ActionFilter can be enabled in this way. If you need to use asp.net core's default dependency injection, you can configure it using AddService. The content of dependency injection will be explained later.
3. Tool class generation
Continue with the legacy of the previous article:
Public static void CreateEntityTypeConfig (Type type)
{
Var targetNamespace = type.Namespace.Replace ("Data.Models", "")
If (targetNamespace.StartsWith (".")
{
TargetNamespace = targetNamespace.Remove (0)
}
Var targetDir = Path.Combine (new [] {CurrentDirect, "Domain.Implements", "EntityConfigures"} .Concat (
TargetNamespace.Split ('.') .ToArray ()
If (! Directory.Exists (targetDir))
{
Directory.CreateDirectory (targetDir)
}
Var baseName = type.Name.Replace ("Entity", "")
If (! string.IsNullOrEmpty (targetNamespace))
{
TargetNamespace = $". {targetNamespace}"
}
Var file = $"using {type.Namespace};" +
$"\ r\ nusing Microsoft.EntityFrameworkCore;" +
$"\ r\ nusing Microsoft.EntityFrameworkCore.Metadata.Builders;" +
$"\ r\ nnamespace Domain.Implements.EntityConfigures {targetNamespace}" +
"\ r\ n {" +
$"\ r\ n\ tpublic class {baseName} Config: IEntityTypeConfiguration" +
"\ r\ n\ t {" +
"\ r\ n\ t\ tpublic void Configure (EntityTypeBuilder builder)" +
"\ r\ n\ t\ t {" +
$"\ r\ n\ t\ tbuilder.ToTable (\" {baseName}\ ");" +
$"\ r\ n\ t\ t\ tbuilder.HasKey (p = > p.Id);" +
"\ r\ n\ t\ t}\ r\ n\ t}\ r\ n}"
File.WriteAllText (Path.Combine (targetDir, $"{baseName} Config.cs"), file)
}
After reading the above, do you have any further understanding of how to use ActionFilter in asp.net core? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
Types and methods of software testing
© 2024 shulou.com SLNews company. All rights reserved.