Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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;
    }
}
like image 710
SBFrancies Avatar asked Jan 03 '18 10:01

SBFrancies


People also ask

What should I return to HttpResponseMessage?

A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action.

How do I return a status code in Web API .NET core?

HTTP Status Code 201 is used to return Created status i.e., when request is completed and a resource is created. Such HTTP Response it is returned using Created function. Optionally, you can also return, the URL where the object is created and also an object along with the HTTP Response Created.


1 Answers

.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

like image 150
Nkosi Avatar answered Sep 27 '22 23:09

Nkosi