Question3r
Question3r

Reputation: 3802

how to return object instead of string with ContentResult

My .NET Core web API project had a sign in POST endpoint and returned the token as a string. Because there was no endpoint url to the generated token resource I didn't return a CreatedAtAction and returned this instead

return new ContentResult
{
    Content = "myToken",
    ContentType = "text/plain",
    StatusCode = 201
};

Now this endpoint returns a class instance holding the access and refresh tokens as properties. Unfortunately the Content property only takes strings. Do I have to convert that object to a string? I think the content type is not plain text anymore. How do I return that object correctly with a 201 statuscode? E.g.

return new ContentResult
{
    Content = classInstanceHoldingTokens,
    ContentType = "this should be json",
    StatusCode = 201
};

When returning ObjectResult it only sends back a 200 statuscode.

Upvotes: 0

Views: 4381

Answers (1)

Vivek Nuna
Vivek Nuna

Reputation: 1

You can simply change the return type to ActionResult and return the response like this. You can create a class according to your requirement.

object results = ...;
return StatusCode(201, results);

Upvotes: 5

Related Questions