[英]How to get ASP.NET Core MVC Filters from HttpContext
I'm trying to write some middleware and need to know if the current action method (if any) has a particular filter attribute, so I can change behaviour based it's existence. 我正在尝试编写一些中间件,并且需要知道当前的操作方法(如果有)是否具有特定的过滤器属性,因此我可以根据其存在来更改行为。
So is it possible to get a filters collection of type IList<IFilterMetadata>
like you do on the ResourceExecutingContext
when you are implementing an IResourceFilter
? 因此,是否有可能像实现
IResourceFilter
时在ResourceExecutingContext
上IList<IFilterMetadata>
那样,获取类型为IList<IFilterMetadata>
的过滤器集合?
It's not really possible today.
今天真的不可能。
It is possible in ASP.NET Core 3.0 在ASP.NET Core 3.0中可能
app.UseRouting();
app.Use(async (context, next) =>
{
Endpoint endpoint = context.GetEndpoint();
YourFilterAttribute filter = endpoint.Metadata.GetMetadata<YourFilterAttribute>();
if (filter != null)
{
}
await next();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
ASP.NET Core 3.0 uses a new routing which every action is an Endpoint
and all attributes on the action and the controller exists on Metadata
. ASP.NET Core 3.0使用新的路由,该路由的每个动作都是一个
Endpoint
并且动作和控制器上的所有属性都位于Metadata
。
Here's how you can do it. 这是您的操作方法。
app.UseRouting();
app.Use(async (context, next) =>
{
Endpoint endpoint = context.GetEndpoint();
YourFilterAttribute filter = endpoint.Metadata.GetMetadata<YourFilterAttribute>();
if (filter != null)
{
}
await next();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Note: Not really answering directly your question, but may help depending of your needs (and the code is too long for comments) 注意:并不是直接回答您的问题,但是根据您的需要可能有所帮助(并且代码太长,无法注释)
Note 2: Not sure if it works on Core, if it doesn't, tell me and I remove the answer 注意2:不确定它是否可以在Core上运行,如果不能,请告诉我,然后删除答案
You can know, in a filter, if another filter is used along with: 您可以知道,在一个过滤器中,是否同时使用了另一个过滤器:
public class OneFilter : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
// Check if the Attribute "AnotherFilter" is used
if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherFilter), true) || filterContext.Controller.GetType().IsDefined(typeof(AnotherFilter), true))
{
// things to do if the filter is used
}
}
}
public class AnotherFilter : ActionFilterAttribute, IActionFilter
{
// filter things
}
AND/OR 与/或
You can put some data in the Route data to let know the Action which Filters are used: 您可以在“路由”数据中放入一些数据,以了解使用了哪些过滤器的“操作”:
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RouteData.Values.Add("OneFilterUsed", "true");
base.OnActionExecuting(filterContext);
}
... ...
public ActionResult Index()
{
if(RouteData.Values["OneFilterUsed"] == "true")
{
}
return View();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.