将查询参数绑定到ASP.NET Core中的模型 [英] Bind query parameters to a model in ASP.NET Core

查看:55
本文介绍了将查询参数绑定到ASP.NET Core中的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从查询参数到对象的模型绑定进行搜索.

I am trying to use model binding from query parameters to an object for searching.

我的搜索对象是

[DataContract]
public class Criteria 
{
  [DataMember(Name = "first_name")]
  public string FirstName { get; set; }
}

我的控制器执行以下操作

My controller has the following action

[Route("users")]
public class UserController : Controller 
{
  [HttpGet("search")]
  public IActionResult Search([FromQuery] Criteria criteria)
  {
    ...
  }
}

当我如下所述调用端点时,.../users/search?first_name=dave控制器操作上的criterias属性为null. 但是,我不能称端点为蛇形.../users/search?firstName=dave,并且criterias属性包含该属性值.在这种情况下,模型绑定有效,但是当我使用snake_case时无效.

When I call the endpoint as follows .../users/search?first_name=dave the criteria property on the controller action is null. However, I can call the endpoint not as snake case .../users/search?firstName=dave and the criteria property contains the property value. In this case Model Binding has worked but not when I use snake_case.

如何在模型绑定中使用snake_case?

How can I use snake_case with Model Binding?

推荐答案

您需要将[FromQuery]属性分别添加到模型属性中

You need to add [FromQuery] attribute to the model properties individually

public class Criteria
{
  [FromQuery(Name = "first_name")]
  public string FirstName { get; set; }
}

这篇关于将查询参数绑定到ASP.NET Core中的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆