Usage scenarios

Calls to API interfaces, especially WPF and background communication, are often encountered during C# development. The called interface accepts only JSON strings.

public String Post(string url, object obj)
{
	using(var client = new HttpClient())
	{
		try
		{
			var str = JsonConvert.SerializeObject(user);
			var content = new StringContent(str,Encoding.UTF8,"application/json");
			HttpResponseMessage response = 
			await client.PostAsync(url, content);
	        response.EnsureSuccessStatusCode();// To throw an exception
	        string responseBody = await response.Content.ReadAsStringAsync();
	        return responseBody;
	    }catch(Exception ex)
	    {
	    }
	    return null;
}
Copy the code

There is a problem

The server uses the API developed in Java, and debugging found that the received JSON object could not be received. But when using Postman calls, the server side accepts normally.

After debugging the WPF breakpoint, it is found that the contentType in the passed content is application/text.

The solution

The modified code is as follows

public String Post(string url, object obj)
{
	using(var client = new HttpClient())
	{
		try
		{
			var str = JsonConvert.SerializeObject(user);
			var content = new StringContent(str,Encoding.UTF8,"application/json");
			content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); // After adding this sentence, the background accepts normally
			HttpResponseMessage response = 
			await client.PostAsync(url, content);
	        response.EnsureSuccessStatusCode();// To throw an exception
	        string responseBody = await response.Content.ReadAsStringAsync();
	        return responseBody;
	    }catch(Exception ex)
	    {
	    }
	    return null;
}
Copy the code

Increase in the content. The Headers. ContentType = System.Net.Http.Headers.MediaTypeHeaderValue (” application/json “); After the code is normal.

To optimize the

You can list the StringContent section as a separate JsonContent class for easy invocation.

class JsonContent: StringContent
{
     public JsonContent(object obj) :
        base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
     {
        this.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); }}Copy the code