【发布时间】:2011-12-22 06:58:08
【问题描述】:
在我的 MVC 3 解决方案中,我希望对查询字符串中的所有 Id 进行加密。要解密我从 DefaultModelBinder 继承并重写 BindProperty 方法的 URL:
public class CryptedIdBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name.ToLower() == "id")
{
propertyDescriptor.SetValue(bindingContext.Model, CryptoHelper.Decrypt(controllerContext.HttpContext.Request.Form["id"]));
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
return;
}
之后我在 Application_Start 的 global.asax 中设置了新的 DefaultBinder:
System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new CryptedIdBinder();
我没有从 IModelBinder 继承,因为我想仅更改解决方案中 id 字段的绑定逻辑。
问题是永远不会调用 BindProperty 方法。我做错了什么?
附言。为了确保我至少调用了 BindModel 方法,我在我的自定义活页夹中添加了这段代码的和平,它被调试器击中:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return base.BindModel(controllerContext, bindingContext);
}
【问题讨论】:
-
你能发布一些示例模型代码吗?也许 DefaultModelBinder 过滤掉了你的一些属性......
-
对不起,我没听懂你的想法。它不是应该为每个模型运行的全局活页夹吗?此 Id 参数未在模型中定义 - 它在默认路由内