Reputation: 3222
When implementing custom filters I am currently using a pattern where my DTOs get both tagged with the filter attribute and also implement a custom interface that exposes some common variables I want to use in my services, for example:
public interface IMyInterface
{
Int32 MyVariable { get; set; }
}
[MyFilter]
public class MyDto
: IMyInterface
{
public Int32 MyVariable { get; set; }
}
public class MyFilterAttribute
: Attribute
, IHasRequestFilter
{
public int Priority { get { return 0; } }
public IHasRequestFilter Copy () { return this; }
public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
var temp = requestDto as IMyInterface;
if( temp != null )
{
var x = [something from the request object...]
temp.MyVariable = x;
}
}
}
Is this the intended pattern? Or is there a way to do it solely with the interface? Is there a way to register a filter for all dtos that implement an inteface via the AppHost?
Upvotes: 2
Views: 566
Reputation: 143339
Unless you have a good reason to the recommendation is to inherit from RequestFilterAttribute which is specifically meant for this purpose which also lets you ignore providing default implementations for Priority and Copy().
If you do want to stick to IHasRequestFilter
then the correct implementation for Copy()
is:
public virtual IHasRequestFilter Copy()
{
return (IHasRequestFilter)this.MemberwiseClone();
}
This ensures that only a Copy is used per request and not the same instance, important to ensure ThreadSafety for when your filters maintaining state.
Upvotes: 1