Web API - 如何返回带有201状态码的动态对象

3

我正在尝试将最近添加的实体ID作为JSON在Web API操作方法中返回。例如:

{ bookId = 666 }

控制器操作代码如下:
[HttpPost, Route("")]
public HttpResponseMessage Add(dynamic inputs)
{
    int bookId = bookService.Add(userId, title);

    dynamic book = new ExpandoObject();
    book.bookId = bookId

    return new HttpResponseMessage(HttpStatusCode.Created)
    {
        Content = new ObjectContent<dynamic>(book,
            new JsonMediaTypeFormatter
            {
                UseDataContractJsonSerializer = true
            })
    };
}

这里的问题是在不使用Dto的情况下返回动态内容并返回HttpStatusCode.Created(201 Http状态)。现在我遇到了以下错误:
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"No se espera el tipo 'System.Dynamic.ExpandoObject' ...
如果我将 new ObjectContent<dynamic> 改为 new ObjectContent<ExpandoObject> ,我会得到正确的 201 状态标头响应,但 JSON 结果如下:
[{"Key":"bookId","Value":666}]

那么,使用动态方式(不是数据传输对象)返回 { bookId: 666 } 并将标头状态代码设置为201(已创建)是否可能?

感谢您的帮助。

1个回答

4
你看到的行为是正确的,因为dynamic / ExpandoObject实际上只是Dictionary<TKey, TValue>的包装器。如果你想将它序列化为对象,则应该使用匿名对象而不是ExpandoObject,例如:
int bookId = bookService.Add(userId, title);

var book = new { bookId = bookId };

return new HttpResponseMessage(HttpStatusCode.Created)
{
    Content = new ObjectContent<object>(book,
        new JsonMediaTypeFormatter
        {
            UseDataContractJsonSerializer = true
        })
};

如果JsonMediaTypeFormatter不支持匿名对象,那么您可以尝试使用默认的序列化器。
return this.Request.CreateResponse(HttpStatusCode.OK, book);

this.Request.CreateResponse(HttpStatusCode.OK, book);的效果非常好。谢谢! - Xavier Egea

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接