我正在尝试将最近添加的实体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(已创建)是否可能?
感谢您的帮助。