【问题标题】:how to return createdatroute location?如何返回 createdatroute 位置?
【发布时间】:2017-05-30 19:27:23
【问题描述】:

我正在尝试创建这样的记录:

[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结果?

【问题讨论】:

    标签: c# asp.net .net asp.net-web-api


    【解决方案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
    

    【讨论】:

    • 我可以确认确实如此。谢谢。简单地在对象中传递 model.id 不会将它们作为查询参数放入
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2017-09-07
    • 2017-06-09
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多