Search code examples
c#asp.net-coreasp.net-core-mvchttpresponsehttpcontent

Can't access the body of HttpResponseMessage


I'm currently working on an API with .NET Core Web App for a test and I'm stuck on this.

Actually, I have this code:

namespace CoreWebApp.API.Admin
{
    [Route("api/country")]
    public class CountryController : Controller
    {
        // GET: api/country
        [HttpGet]
        public HttpResponseMessage Get()
        {
            List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
            return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(countries), Encoding.UTF8, "application/json") };
        }
    }
}

What I'm trying to do is return an HttpStatusCode and an HttpContent. I then should get that on Postman:

[
    {
        "Name":"France"
    },
    {
        "Name":"Germany"
    },
    {
        "Name":"Spain"
    },
    ....
]

StatusCode Ok 200


However, I don't get this body at all, there is what I get:

{
    "version": {
        "major": 1,
        "minor": 1,
        "build": -1,
        "revision": -1,
        "majorRevision": -1,
        "minorRevision": -1
    },
    "content": {
        "headers": [
            {
                "key": "Content-Type",
                "value": [
                    "application/json; charset=utf-8"
                ]
            }
        ]
    },
    "statusCode": 200,
    "reasonPhrase": "OK",
    "headers": [],
    "requestMessage": null,
    "isSuccessStatusCode": true
}

I'm searching for a while now and I'm still unable to get the data in the content, what am I doing wrong? It's my first .NET Core Api so feel free to give any advice if you have some :)

Thanks for any help !


Solution

  • Asp.net core does not support anymore the returning HttpResponseMessage type to resolve your issue the recommended return type is like the following

    [HttpGet]
            public async Task<IActionResult> GeTask()
            {
                List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
                return Ok(countries); 
    }
    

    More here how the ApiController in the full standard .net looks like

    //
            // Summary:
            //     Creates a System.Web.Http.Results.ResponseMessageResult with the specified response.
            //
            // Parameters:
            //   response:
            //     The HTTP response message.
            //
            // Returns:
            //     A System.Web.Http.Results.ResponseMessageResult for the specified response.
            protected internal virtual ResponseMessageResult ResponseMessage(HttpResponseMessage response);
    

    and the source code of controller base class from .net core does not have any definition for HttpResponseMessage