user2916547 user2916547 - 20 days ago 20
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)


and

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

You can use ContentResult:

return new ContentResult() { Content = myContent, StatusCode = myCode };
Comments