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?