0

I have an object as follows:

public class TextMessageInput
{
    public string To { get; set; }
    public string Body { get; set; }
    public string From { get; set; }
}

I am trying to serialize this object and send it to any API with content-type "application/x-www-form-urlencoded". But, I get a 400 Bad request error. It works with string string dataTest = "To=+000000000&Body=hi&From=+00000000";

I understand there is an issue in the serialization. Below is the method I use to serialize

public byte[] SerializeBody(object data)
    {
        return (data == null) ? new byte[0] : Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(data));
    }

I am using System.Net.WebRequest to connect to the APIenter code here, with basic authentication. Could you please suggest the correct way to serialize the object?

akhila
  • 720
  • 2
  • 7
  • 17
  • 1
    Javascript is not `application/x-www-form-urlencoded`...it's Javascript. Don't use the `JavaScriptSerializer`. – Kenneth K. Feb 21 '20 at 20:51
  • @KennethK. Could you please suggest what should I be using to serialize the object? – akhila Feb 21 '20 at 21:07
  • Your best best is to manually serialize your object into a string, perhaps using string interpolation (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) Perhaps add a method like this to your `TextMessageInput` class, then call it to get the serialized string: ```public string Serialize() { return $"To={this.To}&From={this.From}&Body={this.Body}"; }``` – rbonestell Feb 21 '20 at 21:22
  • You can check the FormUrlEncodedContent class here: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=netframework-4.8 .. It is as simple as populating a name/value collection with the parameters you want to send and passing it to this class to get what you need. – Oguz Ozgul Feb 21 '20 at 21:44

0 Answers0