用于GET请求的ASP.NET MVC的自定义模型Binder

Nie*_*ter 19 c# asp.net-mvc http-get custom-model-binder

我已经创建了一个自定义的MVC Model Binder,每次HttpPost进入服务器都会调用它.但不会被HttpGet要求提出要求.

  • 我的自定义模型绑定器是否应该被调用GET?如果是这样,我错过了什么?
  • 如果没有,我怎么可以编写自定义代码处理QueryStringGET请求?

这是我的实施......

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.
   }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax中

protected void Application_Start()
{
   ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
   //...
}
Run Code Online (Sandbox Code Playgroud)

我已经研究过这些解决方案,但它们并不能满足我的需求:

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

备注答案

感谢@Felipe的帮助.为了防止有人与之斗争,我学到了:

  • 定制模型绑定CAN用于GET请求
  • CAN使用DefaultModelBinder
  • 我的想法是动作方法必须有一个参数(否则会跳过模型绑定器的GET请求,这在你想到它时才有意义)

Fel*_*ani 20

让我们说你有自己想要绑定的类型.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    // other properties you need
}
Run Code Online (Sandbox Code Playgroud)

您可以为此特定类型创建自定义模型绑定,继承自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 };
    }
}
Run Code Online (Sandbox Code Playgroud)

Application_Start事件中的Global.asax中,您可以注册此模型绑定,以获取示例:

// for Person type, bind with the PersonModelBinder
ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());
Run Code Online (Sandbox Code Playgroud)

BindModel来自的方法中PersonModelBinder,确保查询字符串中包含所有参数,并为它们提供理想的处理方法.

由于您有此操作方法:

public ActionResult Test(Person person)
{
  // process...
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下网址访问此操作:

Test?id=7&name=Niels&age=25
Run Code Online (Sandbox Code Playgroud)