Home > Enterprise >  How can i escape a string before sending in the body of a Rest request?
How can i escape a string before sending in the body of a Rest request?

Time:05-24

I have a rest request. The body is like the following:

 RestClient client = new RestClient(uri);
 RestRequest request = new RestRequest("", Method.POST);
 request.AddHeader("Authorization", $"Bearer {myToken}");
 request.AddHeader("Content-type", "application/json");
 string json = "{'body': {'contentType': 'html','content': '"   message   "'}}";                    
 request.AddJsonBody(json);
 IRestResponse response = client.Execute(request);

The message contains apostrophes, like John's so the json will be

       string json = "{'body': {'contentType': 'html','content': 'John's'}}";                    

This gives an error, Bad Request. How can i accommodate for this and any other special characters in the message

CodePudding user response:

you have to replace ' with \ "

string json= "{\"body\": {\"contentType\": \"html\",\"content\": \"" message "\"}}";
  • Related