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.

  • 1
    What received on webAPI endpoint? you need to check how objects are deserialized on server. Are properties containing 'long dash' strings? – Pribina Jun 05 '19 at 14:42
  • Possible duplicate of [Passing json data to a WebApi with special characters results to null](https://stackoverflow.com/questions/23760824/passing-json-data-to-a-webapi-with-special-characters-results-to-null) – Pribina Jun 05 '19 at 14:45
  • Its probably client encoding => you need to set up `client.Encoding = Encoding.UTF8;` – Pribina Jun 05 '19 at 14:53
  • Thank you @Pribina It worked like a charm. – Meenakshi Dash Jun 05 '19 at 15:47
  • i posted it as and answer. so you can accept it :) – Pribina Jun 06 '19 at 06:42

1 Answers1

1

Based on comments it could be caused by encoding:

client.Encoding = Encoding.UTF8

Pribina
  • 750
  • 1
  • 7
  • 14