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
  • 4,918
  • 3
  • 28
  • 39
SharpCoder
  • 17,049
  • 41
  • 140
  • 238

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,489
  • 1
  • 14
  • 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,339
  • 3
  • 31
  • 73