[英]How can I code a Created-201 response using IHttpActionResult
How can I code a Created-201 response using IHttpActionResult
?如何使用IHttpActionResult
对 Created-201 响应进行编码?
IHttpActionResult
has only these options IHttpActionResult
只有这些选项
What I am doing now is this code below, but I would like to use IHttpActionResult
and not HttpResponseMessage
我现在正在做的是下面的这段代码,但我想使用IHttpActionResult
而不是HttpResponseMessage
public IHttpActionResult Post(TaskBase model)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model);
response.Headers.Add("Id", model.Id.ToString());
return ResponseMessage(response);
}
If your view derives from ApiController
, you should be able to call the Created
method from base class to create such a response.如果您的视图派生自ApiController
,您应该能够从基类调用Created
方法来创建这样的响应。
Sample:样本:
[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);
}
return Content(HttpStatusCode.Created, "Message");
Content is returning NegotiatedContentResult.内容正在返回 NegotiatedContentResult。 NegotiatedContentResult is implements IHttpActionResult. NegotiatedContentResult 实现了 IHttpActionResult。
A similar problem: If you want to send NotFound with the message.一个类似的问题:如果你想用消息发送 NotFound。
return Content(HttpStatusCode.NotFound, "Message");
Or:或者:
return Content(HttpStatusCode.Created, Class object);
return Content(HttpStatusCode.NotFound, Class object);
In ASP.NET Core, an IActionResult
can be returned.在 ASP.NET Core 中,可以返回IActionResult
。 This means you can return a ObjectResult
with a 201 status code.这意味着您可以返回带有 201 状态代码的ObjectResult
。
[HttpPost]
public async Task<IActionResult> PostAsync([FromBody] CreateModel createModel)
{
// Create domain entity and persist
var entity = await _service.Create(createModel);
// Return 201
return new ObjectResult(entity) { StatusCode = StatusCodes.Status201Created };
}
Alternatively, to what Chris is suggesting, what you can do is return an IActionResult, using or " StatusCode " method, the following way:或者,根据 Chris 的建议,您可以使用或“ StatusCode ”方法返回一个 IActionResult,方法如下:
[HttpPost]
public async Task<IActionResult> PostAsync([FromBody] CreateModel createModel)
{
// Create domain entity and persist
var entity = await _service.Create(createModel);
// Return 201
return StatusCode(StatusCodes.Status201Created, entity);
}
I know this is an old thread but you might want to take a look at my solution here .我知道这是一个旧线程,但您可能想在这里查看我的解决方案。 Its a little more than needed but sure will do the job.它比需要的多一点,但肯定会完成这项工作。
Steps:脚步:
Define a custom attribute:定义自定义属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class UniqueIdAttribute: Attribute
{
}
Decorate the uniquely identifying property of your model with a custom 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; }
}
Add a new Created(T yourobject);
添加一个新的Created(T yourobject);
method to a BaseController which inherits from ApiController.方法到从 ApiController 继承的 BaseController。 Inherit all your controllers from this 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);
}
Its pretty simple without having to worry about writing so much in every method.它非常简单,而不必担心在每种方法中都写这么多。 All you got to do is just call Created(yourobject);
你所要做的就是调用Created(yourobject);
The Created() method would still work if you forget to decorate or cannot decorate your model(for some reason).如果您忘记装饰或无法装饰模型(出于某种原因), Created() 方法仍然有效。 The location header would miss the Id though.但是,位置标头会错过 Id。
Your unit test for that controller should take care of this.您对该控制器的单元测试应该解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.