问题
I am trying to use model binding from query parameters to an object for searching.
My search object is
[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)
{
...
}
}
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.
How can I use snake_case with Model Binding?
回答1:
You need to add [FromQuery]
attribute to the model properties individually
public class Criteria
{
[FromQuery(Name = "first_name")]
public string FirstName { get; set; }
}
回答2:
Solution for .net core 2.1, 2.2 and 3.0
Or without attributes you can do something like this which is cleaner I think (of course if the model properties are same as query parameters).
Meanwhile I use it in .net core 2.1, 2.2 and 3.0 preview 5&6.
public async Task<IActionResult> Get([FromQuery]ReportQueryModel queryModel)
{
}
回答3:
According to @Carl Thomas answer, here is the easier and the strognly typed way to have snake case FromQuery name:
CustomFromQuery
public class CustomFromQueryAttribute : FromQueryAttribute
{
public CustomFromQuery(string name)
{
Name = name.ToSnakeCase();
}
}
StringExtensions
public static class ObjectExtensions
{
public static string ToSnakeCase(this string o) => Regex.Replace(o, @"(\w)([A-Z])", "$1_$2").ToLower();
}
Usage
public class Criteria
{
[CustomFromQuery(nameof(FirstName))]
public string FirstName { get; set; }
}
来源:https://stackoverflow.com/questions/42929376/bind-query-parameters-to-a-model-in-asp-net-core