c# - 如何使用 IHttpActionResult 对 Created-201 响应进行编码

标签 c# asp.net asp.net-web-api response asp.net-web-api2

如何使用 IHttpActionResult 对 Created-201 响应进行编码?

IHttpActionResult 只有这些选项

  • 好的
  • 列表项
  • 未找到
  • 异常(exception)
  • 未经授权
  • 错误请求
  • 冲突重定向
  • 无效模型状态

我现在正在做的是下面这段代码,但我想使用 IHttpActionResult 而不是 HttpResponseMessage

public IHttpActionResult Post(TaskBase model)
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model);
    response.Headers.Add("Id", model.Id.ToString());
    return ResponseMessage(response);
}

最佳答案

如果您的 View 派生自 ApiController,您应该能够从基类调用 Created 方法来创建这样的响应。

示例:

[Route("")]
public async Task<IHttpActionResult> PostView(Guid taskId, [FromBody]View view)
{
    // ... Code here to save the view

    return Created(new Uri(Url.Link(ViewRouteName, new { taskId = taskId, id = view.Id })), view);
}

关于c# - 如何使用 IHttpActionResult 对 Created-201 响应进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23892341/

相关文章:

c# - 使用 asp.net 和状态服务器在两个网站之间共享 session

c# - ASP.NET Web API IExceptionLogger 不捕获异常

c# - PInvoke/Interop 声明

c# - 抽象类列表

c# - 关于使用 backgroundWorker 和异步下载更新表单进度条的建议

asp.net - IIS生成相同的Session.SessionID

c# - 正则表达式 - 20 个字符长的数字,只有空格 如何

c# - SignalR 可以帮助这种情况 - 无需轮询即可检测计划完成情况吗?

asp.net-mvc - ASP.NET WebApi 如何获取 Controller 收到的 JSON

asp.net - Azure ASP.NET Core Web api 对于代理的多部分/表单数据请求返回 404