自定义模型绑定问题
在我的 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);
}
In my MVC 3 solution I want to have all Ids in querystring to be crypted. To decrypt URLs I inherited from DefaultModelBinder and overrided BindProperty method:
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;
}
After that I set new DefaultBinder in global.asax on Application_Start:
System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new CryptedIdBinder();
I didn't inherit from IModelBinder because I want to change binding logic only for id fields in solution.
The issue is that BindProperty method is never called. What am I doning wrong?
PS. In order to be sure that I call at least BindModel method I added a peace of this code inside my custom binder, and it was hit by the debugger:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return base.BindModel(controllerContext, bindingContext);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的模型没有 Id 属性,当然不会调用 BindProperty。因为它调用了模型属性。如果我理解你的问题,你需要的是转换每个 Id 命名查询字符串参数。在这种情况下,您需要一个自定义值提供程序而不是模型绑定程序。这是关于价值的好文章提供商。编写一个非常容易:
在 global.asax 中:
If your models don't have Id properties of course the BindProperty won't be called. Because it called on the model properties. If I understood your question what you need is to transform each Id named query string parameter. In this case you need a custom value provider instead of a modelbinder. This is good article about the value providers. And it's quite easy to write one:
In global.asax: