RestSharp returns 0 for custom ASP.NET Core middleware response

A normal behavior of RestSharp is to return StatusCode = 0 for responses that won’t go through (e.g. unreachable server). However, a tricky behavior of RestSharp is to also return 0 if the response has content, but the Content-Length is undefined.

If you are confused why your RestSharp is returning 0 while Postman and Chrome work fine, make sure you are setting the response Content-Length to the actual content length.

public async Task Invoke(HttpContext context)
//instead of await next(context);
var result = JsonConvert.SerializeObject(new
Message = "Hello, World!"
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.StatusCode = 200;
context.Response.ContentLength = result.Length + 2;
await context.Response.WriteAsync("\r\n" + result);
await context.Response.Body.FlushAsync();