1

I have a requirement where I have been posting data to a web API as a json string in a POST request and the post method retrieves the data from the body. This works perfectly for most data, but it does not work when I include a long dash(—) as part of the data in any fields.

I have a Email class with some string fields and I am passing it to the API to save in the database. Here is how I am implementing the call:

 public string PostNewEmailRecord(string APIEndpoint, CampaignWave Email) { string StrEmailId = string.Empty; _endpoint = APIEndpoint; try { string strData = JsonConvert.SerializeObject(Email); _client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); _client.UploadString(APIEndpoint, _requestType, strData); } catch (Exception ex) { } return StrEmailId; } 

And here is the post method of Web API:

 public void Post([FromBody]CampaignWave email) { try { using (var transaction = new TransactionScope()) { CampaignWaveRepository cr = new CampaignWaveRepository(); object objReturnValue = cr.Insert(email); transaction.Complete(); } } catch (Exception ex) { } finally { } } 

When I include a dash the API post method receives a null value as email.

Please help me how I can successfully pass the '—' without any issue. Thanks in advance.

5
  • 1
    What received on webAPI endpoint? you need to check how objects are deserialized on server. Are properties containing 'long dash' strings? Commented Jun 5, 2019 at 14:42
  • Possible duplicate of Passing json data to a WebApi with special characters results to null Commented Jun 5, 2019 at 14:45
  • Its probably client encoding => you need to set up client.Encoding = Encoding.UTF8; Commented Jun 5, 2019 at 14:53
  • Thank you @Pribina It worked like a charm. Commented Jun 5, 2019 at 15:47
  • i posted it as and answer. so you can accept it :) Commented Jun 6, 2019 at 6:42

1 Answer 1

1

Based on comments it could be caused by encoding:

client.Encoding = Encoding.UTF8

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.