You need a POST request to send an HTML page to the server. HTML stores special characters like <, & etc, due to which server error 500 occurs. Request code:

WebClient webClient = new WebClient(); postParametrs = new NameValueCollection(); postParametrs.Add("Body", body); var response = webClient.UploadValues(url, postParametrs); 

body - the line storing the HTML page, url- address where the request is sent.

How to escape the body string to send its POST request?

  • one
    In fact, the problem is on the server side, it must convert the characters that it considers dangerous to itself. - VladD
  • one
    The server does not have the right to hope for the good intentions of the client. - VladD

3 answers 3

Try using HttpUtility.HtmlEncode(str)

 WebClient webClient = new WebClient(); postParametrs = new NameValueCollection(); body = HttpUtility.HtmlEncode(body); postParametrs.Add("Body", body); var response = webClient.UploadValues(url, postParametrs); 

Well and if it is required on the server use HttpUtility.HtmlDecode(str)

MSDN

  • Unfortunately, your decision does not suit me. I do not have access to the server that receives the request. And if in the body line there is for example "& #" this will cause server 500 error. - mirypoko
  • Input string: <test>&Alib&aba</test> / Output string: &lt;test&gt;&amp;Alib&amp;aba&lt;/test&gt; what doesn't suit you?) - tCode
  • Are you 100% sure that the & character causes an error? - tCode
  • "Are you 100% sure that the & character causes an error?" Not. An error leads to the combination & #. And I do not have the opportunity to decode escaped characters back to the server side which receives a POST request. I need to escape characters in such a way that the recipient server receives pure HTML without escaping by pulling it out of the body request variable - mirypoko

It was possible to send a request without receiving an error when using any characters in this way (using the .net core):

 var httpClient = new HttpClient() var parameters = new Dictionary<string, string> { { "adress", client.Email }, { "body", body}, { "theme", theme } }; var encodedContent = new FormUrlEncodedContent(parameters); var response = await httpClient.PostAsync(url, encodedContent); var content = response.Content; string result = content.ReadAsStringAsync().Result; 

    Try replacing all such characters with special characters, for example

     & = `&amp;`, < = `&lt;`