更改参数名称的Web API模型绑定 [英] Changing the parameter name Web Api model binding
问题描述
我使用的Web API模型绑定从URL解析查询参数。例如,这里是一个模型类:
公共类QueryParameters
{
[需要]
公共字符串帽{搞定;组; } [需要]
公共字符串ID {搞定;组; }
}
当我打电话类似 / API /这工作正常值/ 5 =帽&somecap放大器;?ID = 1
有没有一些方法,我可以改变模型类属性的名称,但保留查询参数的名称相同 - 例如:
公共类QueryParameters
{
[需要]
公共字符串能力{搞定;组; } [需要]
公共字符串ID {搞定;组; }
}
我以为加入 [显示(NAME =帽)]
到能力
属性会的工作,但它没有。是否有某种类型的数据标注,我应该使用?
该控制器将有一个看起来像这样的方法:
公共IHttpActionResult的GetValue([FromUri] QueryParameters参数)
{
//做点什么param.Cap和param.id
}
您可以使用FromUri的名称属性绑定的属性使用不同名称的查询字符串参数的方法的参数。
如果您通过简单的参数,而不是你的 QueryParameters
类型,可以绑定像这样的值:
/ API /价值/ 5 =瓶盖和somecap放大器;?ID = 1公共IHttpActionResult的GetValue([FromUri(NAME =帽子)的字符串功能,INT ID)
{
}
I'm using Web API model binding to parse query parameters from a URL. For example, here is a model class:
public class QueryParameters
{
[Required]
public string Cap { get; set; }
[Required]
public string Id { get; set; }
}
This works fine when I call something like /api/values/5?cap=somecap&id=1
.
Is there some way I can change the name of the property in the model class but keep the query parameter name the same - for example:
public class QueryParameters
{
[Required]
public string Capability { get; set; }
[Required]
public string Id { get; set; }
}
I thought adding [Display(Name="cap")]
to the Capability
property would work, but it doesn't. Is there some type of data annotation I should use?
The controller would be have a method that looked like this:
public IHttpActionResult GetValue([FromUri]QueryParameters param)
{
// Do Something with param.Cap and param.id
}
You can use the Name property of the FromUri binding attribute to use query string parameters with different names to the method arguments.
If you pass simple parameters rather than your QueryParameters
type, you can bind the values like this:
/api/values/5?cap=somecap&id=1
public IHttpActionResult GetValue([FromUri(Name = "cap")] string capabilities, int id)
{
}
这篇关于更改参数名称的Web API模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!