Search code examples
c#httpwebrequest

Custom string from TextBox in webrequest


i am trying to send a HttpWebRequest with the following body :

string body = "{\"prompt\": \"MyText\",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";

the request works perfectly with this body, but everytime i try to change "MyText" with a text from textbox, i get an error 400 from server.

i tried this (return error 400): string body = "{\"prompt\":" +textBox1.Text+",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";

any ideas ?


Solution

  • It is not recommended to build your JSON manually as you will highly expose to syntax errors due to missing/extra quotes, braces, etc especially when dealing with complex objects/arrays.

    Using the libraries such as System.Text.Json or Newtonsoft.Json for the JSON serialization. This is safer and easier compared to building it manually.

    using System.Text.Json;
    
    var obj = new
        {
            prompt = textBox1.Text,
            n = 2,
            size = "256x256",
            response_format = "b64_json"
        };
            
    string body = JsonSerializer.Serialize(obj);
    
    using Newtonsoft.Json;
            
    string body = JsonConvert.SerializeObject(obj);