MVC5 FilterAttributes in ServiceLayer

256 views Asked by At

I want to add a C# FilterAttribute to one of my Service Layer methods. I have gone through lot of examples and all I find is FilterAttributes to decorate Controller Methods. As it is shown in this article, it will all be used as Controller Method attributes.

I have tried both Authorization Filter and Action Filter, both works if I use those to decorate my Controller methods. But if I use those to decorate my Service Layer methods, those do not work.

public class FeatureFilterAttribute : ActionFilterAttribute
{
    public string Feature { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
            filterContext.ActionDescriptor.ActionName);

        base.OnActionExecuting(filterContext);
    }
}

And other thing is you can see I am passing a parameter to the filter.

[FeatureFilter(Feature = FeatureValues.EmailNotifications)]

I tried registering my filters in Global.asax.cs. Then the filter gets called, but I do not get the value for input parameter. I get it as NULL. What am I doing wrong? Or, isn't there a way to use FilterAttributes in a Service Layer method?

My technology stack is basic MVC5. I found lot of stackoverflow questions and answers about FilterAttributes, but not one of those were using attributes in Service Layer.

2

There are 2 answers

0
alekseevi15 On BEST ANSWER

I believe that you should not use ValidationAttribute as well as FilterAttribute to validate your Service layer. They are intended to validate your Presentation layer(via ActionFilters and DataAnnotations).

To validate your Service layer via attributes you could use Interceptors. For example, if you use Castle Windsor you could register interceptor for your service method calls and analyze if method that is being invoked decorated with some validation attribute.

Or if you use WCF for your service layer, you could create your custom validation attributes that implement IParameterInspector interface. Example here.

0
Thilok Gunawardena On

Oops, I got it all wrong I guess, what I need is ValidationAttribute.