CreatedAtRoute使用OK(200)代码

时间:2017-05-31 09:30:34

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

无论是否可接受的RESTful设计,我都希望像下面的代码那样提供结果,但使用200 OK StatusCode。

return CreatedAtRoute("DefaultApi", new { id = model.Id }, model);

上面提供Location标头,它使用给定的id路由变量和json序列化model内容。

return Ok(); // how to make it with this?

请注意,我使用的是ASP.NET WebApi2(.Net 4.6)模板。

1 个答案:

答案 0 :(得分:0)

然后,创建一个自定义SELECT product.product_name AS 'Product Code' , product_sold.reference AS 'Reference' , product_sold.sold_date AS 'Date' FROM product INNER JOIN product_sold USING product_id UNION ALL SELECT product.product_name AS 'Product Code' , product_received.reference AS 'Reference' , product_received.received_date AS 'Date' FROM product INNER JOIN product_received USING product_id 来装饰IHttpActionResult并更新状态代码:

CreatedAtRouteNegotiatedContentResult

然后在你的控制器动作中使用它:

public class OkWithLocation<T> : IHttpActionResult
{
    private readonly CreatedAtRouteNegotiatedContentResult<T> _result;

    public OkWithLocation(CreatedAtRouteNegotiatedContentResult<T> result)
    {
        _result = result;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = await _result.ExecuteAsync(cancellationToken).ConfigureAwait(false);
        response.StatusCode = HttpStatusCode.OK;
        return response;
    }
}

也许不是最漂亮的,但它完成了工作。