1

I am using HttpClient to post some data to a NodeJs based server.

Class Employee
{
      public string Name { get; set; }
}

The functional code:

Employee e = new Employee();
e.Name = "TestUser";
var client = new HttpClient();

var task = client.PostAsJsonAsync(urlTemplate, e);
var result = task.Result.Content.ReadAsStringAsync().Result;

The node application expects a property by name FirstName (instead of Name)

In WCF, we can change the name of DataMember by placing an attribute on top of its definition:

[DataMember(Name = "FirstName")]
public string Name  {   get;   set;  }

Do we have similar option when sending data using HttpClient?

aweis
  • 5,350
  • 4
  • 30
  • 46
SharpCoder
  • 18,279
  • 43
  • 153
  • 249

2 Answers2

2

One option is to use Newtonsoft.Json library. on you model class you can do

Class Employee
{
      [JsonProperty(PropertyName = "FistName")]
      public string Name { get; set; }
}

before you PUT/POST, use JsonConvert.SerializeXXXX function to convert your object into string, and use the string content as your HttpClient payload.

Xiaomin Wu
  • 3,621
  • 1
  • 15
  • 14
0

You can use JSON serialization properties, as outlined in the documentation. Check out the related post: How can I change property names when serializing with Json.net?.

Community
  • 1
  • 1
Igor Ševo
  • 5,459
  • 3
  • 35
  • 80