HttpClient.SendAsync() is not sending JSON as string

Viewed 3353

I'm having trouble figuring out what's wrong with HttpClient script.

When I use Fiddler, it works & AspNetCore MVC isn't throwing errors.

 http://localhost:6004/api/XUnitExamplesTest/JsonStringMethod

 Http-Get

 User-Agent: Fiddler
 Accept: text/json
 Content-Type: text/json
 Host: localhost:6004
 Content-Length: 24

 "{\"Color\": \"Green\"}"

But HttpClient script causing AspNetCore MVC issues.

var sampleData = new XUnitSampleData() { Color = "Red" };
var contentType = "text/json";
var httpMethod = HttpMethod.Get;
var uriPath = "JsonStringMethod";
var jsonData = JsonConvert.SerializeObject(_sampleData, Formatting.None).ToString();  // JSON String.  --> "{ \"Vin\" : \"foo\", \"Color\" : \"foo\" }"
var jsonRequest = string.Format("\"{0}\"", jsonData);

var result = await XUnitWebClient.GetAsync3(contentType, httpMethod, uriPath, jsonRequest, CancellationToken.None);


public static async Task<string> GetAsync3(string contentType, HttpMethod httpMethod, string uriPath, string request, CancellationToken cancellationToken)
{
    using (var httpClient = new HttpClient())  
    {
        using (var httpRequestMessage = new HttpRequestMessage(httpMethod, string.Format("{0}{1}", _uri, uriPath)))
        {
            httpClient.BaseAddress = new Uri(string.Format("{0}", _baseAddress));

            //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));  // "Accept" Header.

            //httpClient.DefaultRequestHeaders.Remove("Content-Type");
            //httpClient.DefaultRequestHeaders.Add("Content-Type", contentType);

            httpRequestMessage.Content = new StringContent(request, Encoding.UTF8, contentType);  // "Content-Type" Header.

            var response = await httpClient.SendAsync(httpRequestMessage);

            return await response.Content.ReadAsStringAsync();
        }
    }
}

AspNetCore MVC got the JSON value as "{".

Since I'm using text/json so how do I tell HttpClient to send json string with beginning quote and ending quote, instead of it stripping that out?

Or am I doing something wrong with JsonConvert.SerializeObject() here?

1 Answers

To answer the question directly...

You're not escaping the quotes inside the JSON string. Try this:

var jsonRequest = string.Format("\"{0}\"", jsonData.Replace("\"", "\\\""));

However...

I question how you're approaching this problem. You mention in your comments that you get an error on the server side (in your MVC code) if you don't stringify the JSON on the client side. However, it is very awkward and non-standard to require the client to do this. I would:

  1. Change the content type from text/json to application/json. That won't fix the problem, but it is the standard.

  2. Remove the line above and send jsonData directly. i.e. don't stringify the JSON.

  3. Ask a new question about how to solve the server-side error you're getting, and post the relevant MVC code.

Related