Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to return the recently added entity Id in a Web Api action method as a JSON. Example:

{ bookId = 666 }

The Controller Action code is as follows:

[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
            })
    };
}

The problem here is to accomplish it returning a dynamic content (without Dto) and returning the HttpStatusCode.Created (201 http status).

Now I have the next error:

{"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' ...

if I change the new ObjectContent<dynamic> by new ObjectContent<ExpandoObject> I get the correct 201 status header response, but the JSON result is as as follows:

[{"Key":"bookId","Value":368752}]

So, is it possible to return { bookId: 368752} using dynamics (not Dtos) setting the header status code to 201 (Created)?

Thank you for your help.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

The behaviour you see is correct because a dynamic / ExpandoObject is effectively just a wrapper around a Dictionary<TKey, TValue>.

If you want it to be serialized as an object then you should use an anonymous object instead of an ExpandoObject e.g.

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
        })
};

If JsonMediaTypeFormatter doesn't support anonymous objects then you could try using the default serializer

return this.Request.CreateResponse(HttpStatusCode.OK, book);
share|improve this answer
    
this.Request.CreateResponse(HttpStatusCode.OK, book); works like a charm. Thank you! –  Freerider Jun 25 at 10:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.