简体   繁体   English

为方法参数创建自定义FilterAttribute

[英]Creating custom FilterAttribute for method parameters

Is it possible to create a custom FilterAttribute for incoming parameters? 是否可以为传入参数创建自定义FilterAttribute? Mostly attributes are used for methods and classes; 通常,属性用于方法和类。

for example my idea is: 例如我的想法是:

public HttpResponseMessage GetAll([CultureInfo]string culture)

{ if(valid) { // code here } }

CultureInfo is a class (CultureInfoAttribute) that inherits from ActionFilterAttribute where i can use 2 methods called, OnActionExecuted and OnActionExecuting. CultureInfo是一个从ActionFilterAttribute继承的类(CultureInfoAttribute),在这里我可以使用2个称为OnActionExecuted和OnActionExecuting的方法。 On top of my class i used the next attribute so i can use it on parameters: 在我的课堂上,我使用了下一个属性,因此可以在参数上使用它:

[AttributeUsage(AttributeTargets.Parameter)]

when i build and i call GetAll("culture") the method OnActionExecuting in my custom filter never gets called....it does when i put the attribute above my method GetAll(). 当我构建并调用GetAll(“ culture”)时,自定义过滤器中的OnActionExecuting方法永远不会被调用....当我将属性放在方法GetAll()上方时,它确实会被调用。

Anyone has expercience with it? 有人有经验吗?

The reason i wanna do this is because i can put attributes on different parameters then instead of the whole method at once. 我想这样做的原因是因为我可以将属性放在不同的参数上,而不是一次将整个方法放在上面。

I think your question is answered here : 我认为您的问题在这里得到了回答:

You should register your filter in GlobalFilters in Global.asax.cs like this: 您应该像这样在Global.asax.cs GlobalFilters中注册过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new CultureInfoAttribute());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM