更改参数名称 Web Api 模型绑定 [英] Changing the parameter name Web Api model binding
问题描述
我正在使用 Web API 模型绑定来解析来自 URL 的查询参数.例如,这是一个模型类:
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; }
}
当我调用诸如 /api/values/5?cap=somecap&id=1
之类的东西时,这很好用.
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; }
}
我认为将 [Display(Name="cap")]
添加到 Capability
属性会起作用,但事实并非如此.我应该使用某种类型的数据注释吗?
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
}
推荐答案
您可以使用 FromUri 绑定属性的 Name 属性来使用与方法参数名称不同的查询字符串参数.
You can use the Name property of the FromUri binding attribute to use query string parameters with different names to the method arguments.
如果你传递简单的参数而不是你的 QueryParameters
类型,你可以像这样绑定值:
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屋!