自定义模型绑定器.. NET MVC上的GET请求

本文关键字:上的 GET 请求 MVC NET 模型 绑定 自定义 | 更新日期: 2023-09-27 18:11:12

我已经创建了一个自定义MVC模型绑定器,每个进入服务器的HttpPost都会被调用。但是没有被HttpGet请求调用。

  • 我的自定义模型binder在GET期间被调用吗?如果是这样,我错过了什么?
  • 如果不是,我怎么写自定义代码处理GET请求的QueryString ?

这是我的实现…

public class CustomModelBinder : DefaultModelBinder
{
   public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
      // This only gets called for POST requests. But I need this code for GET requests.
   }
}

Global.asax

protected void Application_Start()
{
   ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
   //...
}

我已经研究了这些解决方案,但是它们不太适合我正在寻找的:

  • 通过TempData持久化复杂类型
  • 使用默认绑定器构建复杂类型(?Name=John&Surname=Doe)

回答注释

感谢@Felipe的帮助。为了防止有人遇到同样的问题,我学会了:

  • 定制模型绑定器可以用于GET请求
  • 可以使用DefaultModelBinder
  • 我的障碍是动作方法必须有一个参数(否则模型绑定器将跳过GET请求,当你考虑它时,这是有意义的)

自定义模型绑定器.. NET MVC上的GET请求

假设您有自己想要绑定的类型。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    // other properties you need
}

您可以为这个特定的类型创建一个自定义模型绑定,继承自DefaultModelBinder,例如:

public class PersonModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        int id = Convert.ToInt32(request.QueryString["id"]);
        string name = request.QueryString["name"];
        int age = Convert.ToInt32(request.QueryString["age"]);
        // other properties
        return new Person { Id = id, Name = name, Age = age };
    }
}

在全局。在Application_Start事件中,您可以注册此模型绑定,例如:

// for Person type, bind with the PersonModelBinder
ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());

PersonModelBinderBindModel方法中,确保您拥有querystring中的所有参数,并给予它们理想的处理。

既然你有这个动作方法:

public ActionResult Test(Person person)
{
  // process...
}

你可以用url访问这个动作,像这样:

Test?id=7&name=Niels&age=25