简体   繁体   English

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

[英]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只有这些选项

  • Ok
  • List item项目清单
  • NotFound未找到
  • Exception例外
  • Unauthorized未经授权
  • BadRequest错误的请求
  • Conflict Redirect冲突重定向
  • InvalidModelState无效模型状态

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.

相关问题 我应该如何填充我的 201 Created 响应? - How should I populate my 201 Created response? 如何在 IHttpActionResult 的响应正文中添加“代码”返回 BadRequest(Message) - How to add "code" in Response Body of IHttpActionResult return BadRequest(Message) 如何从 Web ZDB9344238708A3A8 - How can I return a JSON object and status code (IHttpActionResult) from an ExceptionHandler in Web API? 如何将 Uri 添加到 Post 请求的 Created(状态代码 201) - How to Add Uri to the Created(Status Code 201) of a Post Request 如何获得非201状态码的响应流 - How to get the response stream on a non 201 status code 如何将 IHttpActionResult(包含 JSON)转换为我可以使用 LINQ 处理的对象 - How to convert an IHttpActionResult (with JSON inside) to an object I can process with LINQ 如何显示来自 c # 中的 IHttpActionResult 的 Ok () 消息? - How can I display the Ok () message from the IHttpActionResult in c #? 如何返回带有Http状态码200的IHttpActionResult并在http响应中传递内存流 - How to return a IHttpActionResult with Http status code 200 and pass in a memory stream in the http response 如何获取Web API IHttpActionResult响应并序列化c# - How get Web API IHttpActionResult response and serialize c# 如何设置返回 IHttpActionResult 的模拟? - How do I setup a mock that returns IHttpActionResult?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM