使用自定义ASP.NET MVC IValueProvider,而不是全局设置?

时间:2011-09-29 16:08:33

标签: asp.net-mvc model-binding modelbinders value-provider

我希望能够从cookie中获取键/值并使用它来绑定模型。

我认为DefaultModelBinder不是构建自定义的ModelBinder,而是开箱即用,选择值来自哪里的最佳方法是设置它使用的IValueProvider。

为此,我不想创建自定义的ValueProviderFactory并将其全局绑定,因为我只希望在特定的操作方法中使用此ValueProvider。

我已经构建了一个执行此操作的属性:

/// <summary>
/// Replaces the current value provider with the specified value provider
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SetValueProviderAttribute : ActionFilterAttribute
{
    public SetValueProviderAttribute(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    private Type _ValueProviderType;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        IValueProvider valueProviderToAdd = GetValueProviderToAdd();

        filterContext.Controller.ValueProvider = valueProviderToAdd;
    }

    private IValueProvider GetValueProviderToAdd()
    {
        return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
    }
}

不幸的是,ModelBinder及其IValueProvider是在OnActionExecuting之前设置的(为什么?????)。有没有其他人想办法在不使用ValueProviderFactory的情况下将自定义IValueProvider注入DefaultModelBinder?

3 个答案:

答案 0 :(得分:10)

在这种情况下,您仍应使用ValueProviderFactory

您必须在ValueProviderFactory上实施的方法具有以下签名:

IValueProvider GetValueProvider(ControllerContext controllerContext)

在您的方法实现中,您可以检查控制器上下文,如果传入请求是针对您要利用cookie的控制器/操作,请返回一些CustomCookieValueProvider

如果您不想为请求利用cookie,只需返回null,框架将从Value Provider列表中筛选出来。

作为奖励,您可能不希望硬编码何时将CustomCookieValueProvider用于ValueProviderFactory的逻辑。或许,您可以利用DataTokens来匹配何时使用给定路线的Cookie。所以添加这样的路线:

routes.MapRoute("SomeRoute","{controller}/{action}").DataTokens.Add("UseCookies", true);

注意那里的DataTokens.Add()电话,现在在GetValueProvider方法内你可以这样做:

if (controllerContext.RouteData.DataTokens.ContainsKey("UseCookies"))
{
    return new CustomCookieValueProvider(controllerContext.RequestContext.HttpContext.Request.Cookies);
}

return null;

答案 1 :(得分:3)

想出如何做到这一点。首先,创建一个自定义模型绑定器,它在构造函数中采用值提供程序类型 - 但继承自默认的模型绑定器。这允许您使用标准模型绑定与自定义值提供程序:

/// <summary>
/// Uses default model binding, but sets the value provider it uses
/// </summary>
public class SetValueProviderDefaultModelBinder : DefaultModelBinder
{
    private Type _ValueProviderType;

    public SetValueProviderDefaultModelBinder(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    /// <summary>
    /// Before binding the model, set the IValueProvider it uses
    /// </summary>
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ValueProvider = GetValueProvider();

        return base.BindModel(controllerContext, bindingContext);
    }

    private IValueProvider GetValueProvider()
    {
        return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
    }
}

然后我们创建一个模型绑定属性,它将在上面创建的自定义模型绑定器中注入值提供程序类型,并将其用作模型绑定器:

/// <summary>
/// On the default model binder, replaces the current value provider with the specified value provider.  Cannot use custom model binder with this.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public class SetValueProviderAttribute : CustomModelBinderAttribute
{
    // Originally, this was an action filter, that OnActionExecuting, set the controller's IValueProvider, expecting it to be picked up by the default model binder
    // when binding the model.  Unfortunately, OnActionExecuting occurs AFTER the IValueProvider is set on the DefaultModelBinder.  The only way around this is
    // to create a custom model binder that inherits from DefaultModelBinder, and in its BindModel method set the ValueProvider and then do the standard model binding.

    public SetValueProviderAttribute(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    private Type _ValueProviderType;

    public override IModelBinder GetBinder()
    {
        var modelBinder = new SetValueProviderDefaultModelBinder(_ValueProviderType);
        return modelBinder;
    }
}

答案 2 :(得分:3)

这是一个替代方案,允许您将IValueProviders指定为针对操作参数的属性。 这使得IValueProviders成为瞬态而非全局。

public interface IControllerContextAware
{
    ControllerContext ControllerContext { get; set; }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class ValueProviderAttribute : CustomModelBinderAttribute
{
    public Type[] ValueProviders { get; private set; }

    public ValueProviderAttribute(params Type[] valueProviders)
    {
        if (valueProviders == null)
        {
            throw new ArgumentNullException("valueProviders");
        }
        foreach (var valueProvider in valueProviders.Where(valueProvider => !typeof(IValueProvider).IsAssignableFrom(valueProvider)))
        {
            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The valueProvider {0} must be of type {1}", valueProvider.FullName, typeof(IValueProvider)), "valueProviders");
        }

        ValueProviders = valueProviders;
    }

    public override IModelBinder GetBinder()
    {
        return new ValueProviderModelBinder
            {
                ValueProviderTypes = ValueProviders.ToList(),
                CreateValueProvider = OnCreateValueProvider
            };
    }

    protected virtual IValueProvider OnCreateValueProvider(Type valueProviderType, ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProvider = (IValueProvider)Activator.CreateInstance(valueProviderType);
        if (valueProvider is IControllerContextAware)
        {
            (valueProvider as IControllerContextAware).ControllerContext = controllerContext;
        }
        return valueProvider;
    }

    private class ValueProviderModelBinder : DefaultModelBinder
    {
        public IList<Type> ValueProviderTypes { get; set; }
        public Func<Type, ControllerContext, ModelBindingContext, IValueProvider> CreateValueProvider { get; set; }

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviders = from type in ValueProviderTypes
                                 select CreateValueProvider(type, controllerContext, bindingContext);

            bindingContext.ValueProvider = new ValueProviderCollection(valueProviders.Concat((Collection<IValueProvider>)bindingContext.ValueProvider).ToList());

            return base.BindModel(controllerContext, bindingContext);
        }
    }
}

这基本上是ModelBinderAttribute的代码形式,但有一些调整。 它没有密封,因此您可以根据需要更改IValueProviders的创建方式。

这是一个简单的示例,它查看另一个字段,可能是隐藏或加密的字段,并获取数据并将其放入另一个属性。

这是模型,它不了解IValueProvider,但知道隐藏的字段。

public class SomeModel
{
    [Required]
    public string MyString { get; set; }

    [Required]
    public string MyOtherString { get; set; }

    [Required]
    public string Data { get; set; }
}

我们有IValueProvider,在这种情况下,我的提供者明确知道我的模型,但事实并非如此。

public class MyValueProvider : IValueProvider, IControllerContextAware
{
    public ControllerContext ControllerContext { get; set; }

    public bool ContainsPrefix(string prefix)
    {
        var containsPrefix = prefix == "MyString" && ControllerContext.HttpContext.Request.Params.AllKeys.Any(key => key == "Data");
        return containsPrefix;
    }

    public ValueProviderResult GetValue(string key)
    {
        if (key == "MyString")
        {
            var data = ControllerContext.RequestContext.HttpContext.Request.Params["Data"];

            var myString = data.Split(':')[1];

            return new ValueProviderResult(myString, myString, CultureInfo.CurrentCulture);
        }
        return null;
    }
}

然后将所有这些联系在一起的行动:

    [HttpGet]
    public ActionResult Test()
    {
        return View(new SomeModel());
    }

    [HttpPost]
    public ActionResult Test([ValueProvider(typeof(MyValueProvider))]SomeModel model)
    {
        return View(model);
    }