user2916547 user2916547 - 1 year ago 85
C# Question

How to return both custom HTTP status code and content?

I have an WebApi Controller written in ASP.NET Core and would like to return a custom HTTP status code along with custom content.

I am aware of:

return new HttpStatusCode(myCode)


return Content(myContent)

and I am looking for something along the lines of:

return Content(myCode, myContent)

or some in built mechanism that already does that. So far I have found this solution:

var contentResult = new Content(myContent);
contentResult.StatusCode = myCode;
return contentResult;

is another recommended way of achieving this?

Answer Source

You can use ContentResult:

return new ContentResult() { Content = myContent, StatusCode = myCode };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download