SBFrancies
SBFrancies

Reputation: 4250

.Net Core returning an int in HttpResponseMessage

I'm trying to replicate the following ASP.Net code in .Net Core:

return Request.CreateResponse( HttpStatusCode.OK, 100 );

I have tried:

using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms))
    {
        sw.Write(100);
        return new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(sw.BaseStream)};
    }
}

but it is not giving me the result I would like. I'm working with a legacy API which must read an integer from the response stream so I don't have the option of changing the design.

Below is the code which receives the response, the TryParse always fails, I need it to succeed. Unfortunately I have no way of debugging it:

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    string result = reader.ReadToEnd();

    int value = 0;

    if (Int32.TryParse(result, out value))
    {
        return value;
    }
}

Upvotes: 7

Views: 9897

Answers (1)

Nkosi
Nkosi

Reputation: 247551

.net-core no longer returns HttpResponseMessage.

Controller has helper methods that allow you to return specific IActionResult results/responses..

like

public IActionResult MyControllerAction() {
    //...

    return Ok(100);
}

which will return a HTTP 200 response with 100 in the body of the response

Upvotes: 11

Related Questions