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

问题描述 投票:15回答:3

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

IHttpActionResult只有这些选择

  • 项目清单
  • 未找到
  • 例外
  • 擅自
  • 错误请求
  • 冲突重定向
  • InvalidModelState

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

 public IHttpActionResult Post(TaskBase model)
        {
           HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model);
          response.Headers.Add("Id", model.Id.ToString());
          return ResponseMessage(response);
         }
c# asp.net asp.net-web-api response asp.net-web-api2
3个回答
14
投票

如果您的视图派生自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);
}

5
投票
return Content(HttpStatusCode.Created, "Message");

内容返回NegotiatedContentResult。 NegotiatedContentResult实现了IHttpActionResult。

enter image description here

enter image description here

类似的问题:如果你想发送带有消息的NotFound。

return Content(HttpStatusCode.NotFound, "Message");

要么:

return Content(HttpStatusCode.Created, Class object);
return Content(HttpStatusCode.NotFound, Class object);

-1
投票

我知道这是一个老线程,但你可能想看看我的解决方案here。它比需要的多一点,但肯定会完成这项工作。

脚步:

定义自定义属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class UniqueIdAttribute: Attribute
    {
    }

使用自定义属性装饰模型的唯一标识属性:

   public class Model
    {
        public List<Model> ChildModels { get; set; }
        [UniqueId]
        public Guid ModelId { set; get; }
        public Guid ? ParentId { set; get; }
        public List<SomeOtherObject> OtherObjects { set; get; }
    }

将新的Created(T yourobject);方法添加到继承自ApiController的BaseController。从这个BaseController继承所有控制器:

CreatedNegotiatedContentResult<T> Created<T>(T content)
    {
        var props =typeof(T).GetProperties()
        .Where(prop => Attribute.IsDefined(prop, typeof(UniqueIdAttribute)));
        if (props.Count() == 0)
        {
            //log this, the UniqueId attribute is not defined for this model
            return base.Created(Request.RequestUri.ToString(), content);
        }
        var id = props.FirstOrDefault().GetValue(content).ToString();
        return base.Created(new Uri(Request.RequestUri + id), content);
     }

它非常简单,无需担心在每种方法中都写得那么多。你所要做的只是打电话给Created(yourobject);

如果您忘记装饰或无法装饰模型(由于某种原因),Created()方法仍然有效。虽然位置标题会遗漏Id。

您对该控制器的单元测试应该注意这一点。

© www.soinside.com 2019 - 2024. All rights reserved.