简体   繁体   中英

.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;
    }
}

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM