jump4791
jump4791

Reputation: 1233

ASP.NET Core WebApi HttpResponseMessage create custom message?

How can I create custom message in ASP.NET Core WebApi ? For example I want to return

new HttpResponseMessage()
{
    StatusCode=HttpStatusCode.OK,
    Message="Congratulations !!"
};

new HttpResponseMessage()
{ 
    StatusCode=HttpStatusCode.NotFound,
    Message="Sorry !!"
};

Upvotes: 15

Views: 41756

Answers (3)

Gaurav Sharma
Gaurav Sharma

Reputation: 11

Instead of CreateResponse you can use the StatusCode. The StatusCode is in the namespace Microsoft.AspNetCore.Mvc.

public virtual ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] object value);

Below is syntax.

return StatusCode(Convert.ToInt32(returnstatus.StatusCode), senderResponse);

Return type of the method will be IActionResult

Upvotes: 0

Yang Zhang
Yang Zhang

Reputation: 4570

In order to return legacy HttpResponseMessage, you need to convert it to ResponseMessageResult in .net core. The following is an example.

    public async Task<IActionResult> Get(Guid id)
    {
        var responseMessage = HttpContext.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK,
            new YourObject()
            {
                Id = Id,
                Name = Name
            });

        return new ResponseMessageResult(responseMessage);
    }

Upvotes: 5

Jared Kells
Jared Kells

Reputation: 7052

This simplest method is to use the helpers from the base Controller class.

public ActionResult ExampleNotFound()
{
    return NotFound("Sorry !!");            
}

public ActionResult ExampleOk()
{
    return Ok("Congratulations !!");
}

Alternatively you can return a new ContentResult and set it's status code.

return new ContentResult
     {
         Content = "Congratulations !!",
         ContentType = "text/plain",
         StatusCode = 200
     };

These two methods are slightly different, the ContentResult will always have a ContentType of text/plain

The Ok() and NotFound() methods return an ObjectResult which uses a formatter to serialize your string according to the content types in the Accept header from the request.

Upvotes: 21

Related Questions