我正在尝试创建这样的记录:
[Route("", Name = "CreateAccount")]
[HttpPost]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account)
{
var response = await _accountService.Create(account);
return CreatedAtRoute(
routeName: "GetAccount",????);
}
记录的创建成功;然而。我不确定如何返回CreatedAtRoute
对象?
这是我的GET控制器方法:
[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
var query = Request.RequestUri.PathAndQuery.Split('/')[2];
var response = _accountService.Get(query);
if (!response.Result.IsSuccessStatusCode)
{
return NotFound();
}
var readAsAsync = response.Result.Content.ReadAsAsync<object>();
if (readAsAsync == null)
{
return NotFound();
}
var result = await readAsAsync;
return Ok(result);
}
你可以看到控制器不接受任何参数,而是从Request.RequestUri.PathAndQuery
创建记录后,我们如何返回有效的CreatedAtRoute
结果?
答案 0 :(得分:1)
您可以尝试的一件事是将路线值作为对象传递。框架应将它们(路由值)转换为查询字符串。
[HttpPost]
[Route("", Name = "CreateAccount")]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account) {
var response = await _accountService.Create(account);
var model = await response.Content.ReadAsAsync<MyModel>();
return CreatedAtRoute(
routeName: "GetAccount",
routeValues: new { id = model.Id, name = model.Name }, // can include other properties
content: model);
}
这应该在201响应中设置位置标题,如
LOCATION: http://localhost/api/accounts?id=5&name=JDoe