【发布时间】:2018-12-11 16:37:36
【问题描述】:
考虑以下示例:
[HttpGet("api/values/{id}")]
public ActionResult<string> Get(int id)
{
return id
}
以上内容可以毫无问题地工作,但是,我希望对其进行更改,以便允许为参数说 10 个参数。我试图在一个安静的 api 场景中理解这是如何完成的。
第一个问题是它在 URI 端的外观如何? api/values/5/testOne/TestTwo/?如果 testOne 为空怎么办?那么我应该使用查询参数吗? api/values/5/?testOne=abc&testTwo=123
第二个是我可以将它包装在我所谓的请求模型中吗?例子: 假设我有一个这样的请求模型:
public class TestRequestModel
{
public int Id { get; set; }
public string TestOne { get; set; }
public string TestTwo { get; set; }
}
假设我希望包含它:
[HttpGet("api/values/{id}/{testOne}/{testTwo}")]
public ActionResult<string> Get(TestRequestModel requestModel)
{
return requestModel.Id
}
上面的 {id} 不会映射到 requestModle.Id,其他参数也不会。我的第二个问题是如何在 GET 请求中实现该绑定?
【问题讨论】:
-
尝试
api/values/5//TestTwo/将null传递给URL 中的testOne参数。 -
使用
[FromRoute] TestRequestModel requestModel。 -
@KirkLarkin 对查询字符串有效还是仅对设置路由有效?
-
那是“设置路线”(你的第二个例子)。
标签: c# rest api asp.net-core-mvc restful-url