.Net Core returns int in HttpResponseMessage

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

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

I 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 that does not give me the result that I would like. I am working with an outdated API that needs to read an integer from a response stream, so I have no way to change the design.

Below is the code that gets the answer, TryParse always fails, I need it to work out. Unfortunately, I have no way to debug it:

 using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); int value = 0; if (Int32.TryParse(result, out value)) { return value; } } 
+6
source share
2 answers

.net-core no longer returns HttpResponseMessage .

The controller has helper methods that allow you to return specific IActionResult results and responses.

as

 public IActionResult MyControllerAction() { //... return Ok(100); } 

which will return an HTTP 200 response with 100 in the response body

+6
source

To return an obsolete HttpResponseMessage , you need to convert it to a ResponseMessageResult in the .net core. The following is an example.

  public async Task<IActionResult> Get(Guid id) { var responseMessage = HttpContext.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, new YourObject() { Id = Id, Name = Name }); return new ResponseMessageResult(responseMessage); } 
0
source

Source: https://habr.com/ru/post/1274463/


All Articles