Ovi
Ovi

Reputation: 2750

RESTful service return HTTP Response with Message

How is it possible to leverage the HTTP Status Codes in REST services on aspnet core? Eventually even including a message if something went wrong.

For example:

    [HttpGet]
    public async Task<MyModel> Get(int id)
    {
        if (id == 0)
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        ...
    }

this code obviously returns the error Cannot implicitly convert type 'System.Net.Http.HttpResponseMessage' to 'MyModel'

One solution would be to always return a HTTP200 and a couple of extra properties to MyModel like Status, Success or Message, but this defeats the purpose of being RESTful.

Upvotes: 0

Views: 2771

Answers (3)

UserSud
UserSud

Reputation: 21

This worked for me instead

 return BadRequest("Something is not correct");

Upvotes: 0

Nate Barbettini
Nate Barbettini

Reputation: 53710

Instead of returning Task<MyModel>, return Task<IActionResult>:

[HttpGet]
public async Task<IActionResult> Get(string id)
{
    if (id == 0) return BadRequest();
    // ...

    return Ok(model);
}

There are a number of controller helper methods (see the documentation) such as BadRequest(), Ok(), NotFound(), Created(), and so on. These map onto the HTTP response codes that you'd expect.

Upvotes: 2

Shyju
Shyju

Reputation: 218962

You can use the Ok or BadRequest method. You can use Task<ObjectResult> as your return type.

[HttpGet]
public async Task<ObjectResult> Get(int id)
{
   if(id==0)
      return BadRequest(new {Messagae = "Something is not correctT"});
   var result = await GetSomeMyModelObject();

   return Ok(result);
}

You do not need to necessarily call Ok method, you can simply return your data. The serializer will take care of setting the correct response headers (200 OK status) This will also work

[HttpGet]
public async Task<IActionResult> Get(int id)
{
   if(id==0)
      return BadRequest(new {Messagae = "Something is not correctT"});
   var result = await GetSomeMyModelObject();

   return result;
}

Upvotes: 1

Related Questions