在我的自定义模型活页夹中,我使用

bindingContext.ValueProvider.GetValue(propertyName);

我的操作确实有 [ValidateInput(false)] 。但是,上面的GetValue调用导致

从客户端中检测到一个潜在危险的Request.QueryString值

如何使我的自定义模型活页夹从值提供者获取未验证的值?当然,当发现操作上存在ValidateInput(false)时。

最佳答案

以防万一有人好奇,这是一个快速的解决方案。只需在BindModel/BindProperty方法中调用CheckUnvalidated()。这会将默认的QueryStringValueProvider替换为未经验证的版本。

  MethodInfo GetActionMethod(ControllerContext controllerContext)
  {
     var action = controllerContext.RouteData.Values["action"] as string;
     return controllerContext.Controller.GetType().GetMethods().FirstOrDefault(x => x.Name == action ||
        x.GetCustomAttribute<ActionNameAttribute>().SafeGet(a => a.Name) == action);
  }

  void CheckUnvalidated(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
     var method = GetActionMethod(controllerContext);
     if (method == null)
        return;
     if (method.GetCustomAttribute<ValidateInputAttribute>().SafeGet(x => x.EnableValidation, true))
        return;
     var collection = bindingContext.ValueProvider as ValueProviderCollection;
     if (collection == null)
        return;
     var old = collection.OfType<QueryStringValueProvider>().FirstOrDefault();
     if (old != null)
        collection.Remove(old);
     collection.Add(new UnvalidatedQueryStringValueProvider(controllerContext));
  }

  class UnvalidatedQueryStringValueProvider : NameValueCollectionValueProvider
  {
     public UnvalidatedQueryStringValueProvider(ControllerContext controllerContext)
        : base(controllerContext.HttpContext.Request.Unvalidated().QueryString, CultureInfo.InvariantCulture)
     {
         }
  }

关于asp.net-mvc - 未验证的IValueProvider.GetValue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6412615/

10-13 05:35