Issue #312 - TypeFilterAttribute (with sample).

Implmentation for understanding and consuming ITypeFilter was already
there.
This commit is contained in:
Ryan Nowak 2014-04-25 15:20:52 -07:00
parent fe6f023948
commit 2ad1cca549
6 changed files with 35 additions and 4 deletions

View File

@ -2,12 +2,12 @@
namespace MvcSample.Web.Filters
{
public class UserNameProvider : ActionFilterAttribute
public class UserNameProvider : IActionFilter
{
private static readonly string[] _userNames = new[] { "Jon", "David", "Goliath" };
private static int _index;
public override void OnActionExecuting(ActionExecutingContext context)
public void OnActionExecuting(ActionExecutingContext context)
{
object originalUserName = null;
@ -20,5 +20,9 @@ namespace MvcSample.Web.Filters
context.ActionArguments["userName"] = _userNames[(_index++)%3];
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
}

View File

@ -11,7 +11,7 @@ namespace MvcSample.Web
[PassThrough(Order = 2)]
[InspectResultPage]
[BlockAnonymous]
[UserNameProvider(Order = -1)]
[TypeFilter(typeof(UserNameProvider), Order = -1)]
public class FiltersController : Controller
{
public User User { get; set; }

View File

@ -73,7 +73,10 @@ namespace Microsoft.AspNet.Mvc.Filters
throw new InvalidOperationException("Type filter must implement IFilter");
}
var typeFilter = _typeActivator.CreateInstance(ServiceProvider, typeFilterSignature.ImplementationType) as IFilter;
var typeFilter = (IFilter)_typeActivator.CreateInstance(
ServiceProvider,
typeFilterSignature.ImplementationType,
typeFilterSignature.Arguments);
ApplyFilterToContainer(typeFilter, filter);
filterItem.Filter = typeFilter;

View File

@ -4,6 +4,8 @@ namespace Microsoft.AspNet.Mvc
{
public interface ITypeFilter : IFilter
{
object[] Arguments { get; }
Type ImplementationType { get; }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Diagnostics;
namespace Microsoft.AspNet.Mvc
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
[DebuggerDisplay("TypeFilter: Type={ImplementationType} Order={Order}")]
public class TypeFilterAttribute : Attribute, ITypeFilter, IOrderedFilter
{
public TypeFilterAttribute(Type type)
{
ImplementationType = type;
}
public object[] Arguments { get; set; }
public Type ImplementationType { get; private set; }
public int Order { get; set; }
}
}

View File

@ -73,6 +73,7 @@
<Compile Include="DefaultControllerFactory.cs" />
<Compile Include="DefaultParameterDescriptorFactory.cs" />
<Compile Include="Extensions\IEnumerableExtensions.cs" />
<Compile Include="Filters\TypeFilterAttribute.cs" />
<Compile Include="Filters\ActionExecutedContext.cs" />
<Compile Include="Filters\ActionExecutingContext.cs" />
<Compile Include="Filters\ActionExecutionDelegate.cs" />