skip to Main Content

I am calling an API with :

content =  await request.Content.ReadAsStringAsync();
var response = req.CreateResponse(request.StatusCode);
await response.WriteAsJsonAsync(content, request.StatusCode);

return response;

and it seems to be ok and working but the JSON is coming out like this:

"{"Policy_reference":"P12300025"}"

full code:

var data = new StringContent(requestBody, Encoding.UTF8, "application/json");
var request = await GetSubmissions.PostAsync("api", data);
                        
if (request.IsSuccessStatusCode)
{
    content =  await request.Content.ReadAsStringAsync();
    var response = req.CreateResponse(request.StatusCode);
    await response.WriteAsJsonAsync(content, request.StatusCode);
    
    return response;
}

Thanks

This now working becasue I have implemented WriteStringAsync but i am receiving text in postman
enter image description here

2

Answers


  1. WriteAsJsonAsync is encoding the value you give it to a JSON, so you are essentially double-encoding the string. Instead you should use `WriteAsync’:

    content =  await request.Content.ReadAsStringAsync();
    var response = req.CreateResponse(request.StatusCode);
    await response.WriteAsync(content);
    
    return response;
    
    Login or Signup to reply.
  2. Your are trying to write a string as JSON, so you will encounter double serialization, just write it as string. Assuming you are using HttpResponseDataExtensions.WriteAsJsonAsync, then you can try HttpResponseDataExtensions.WriteStringAsync:

    await response.WriteStringAsync(content);
    

    Or try WriteAsync from HttpResponseWritingExtensions:

    await response.WriteAsync(content);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search