Home > Blockchain >  Can I get request body as string in .Net 5.0?
Can I get request body as string in .Net 5.0?

Time:10-20

We have a http server. The server receive http post requests with json body. But sometimes the json object came invalid. In this case we want to read body as string. How can i implement that in .Net 5.0.

Thanks.

My Code :

        [HttpPost]
        [Route("api")]
        public async Task<string> api([FromBody] string requestContent)
        {
             // When invalid json request receieve, requestContent is null  
           return requestContent;
        } 

CodePudding user response:

You can read the body outside of controller flow. But firstly, you should activate request body buffering. On the Configure method of Startup class use this middleware before app.UseEndpoints.

app.Use(async (context, next) =>
{
   context.Request.EnableBuffering();
   await next.Invoke();
});

Then you can read body from any action like this:

Request.Body.Seek(0, SeekOrigin.Begin)
var body = await new StreamReader(Request.Body).ReadToEndAsync();

CodePudding user response:

Well better would be rather than sending the body as json, you should send as string format. For examples with the current code snippet provided by you:

request :

"{\"username\":\"ak\", \"password\": \"142437630028jdnj\"}"

response :

{"username":"ak", "password": "142437630028jdnj"}

You have to parse the json body to string before sending them like below:

JObject.Parse(str);
  • Related