How to send arbitrary JSON data with a custom header to a REST server?

TL; DR - How to send a JSON string to a REST host with auth header? I tried using three different approaches that work with anonymous types. Why can't I use anonymous types? I need to set a variable called "Group-Name", and the hyphen is not a valid C # identifier.

Background

I need POST JSON, but I cannot get the body and type of content correctly

Function # 1 - works with anonymous types

The content type and data are correct, but I do not want to use anonymous types. I want to use a string

static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(restURLBase); client.DefaultRequestHeaders.Add("Auth-Token", AuthToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // StringContent content = new StringContent(postBody); var test1 = "data1"; var test2 = "data2"; var test3 = "data3"; var response = client.PostAsJsonAsync(RESTUrl, new { test1, test2, test3}).Result; // Blocking call! if (!response.IsSuccessStatusCode) { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); return; } } 

Exit # 1

The content type and data is correct when using AnonymousTypes + PostAsJsonAsync, but I do not want to use anonymous types.

 POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1 Auth-Token: --- REDACTED ----- Accept: application/json Content-Type: application/json; charset=utf-8 Host: api.dynect.net Content-Length: 49 Expect: 100-continue {"test1":"data1","test2":"data2","test3":"data3"} 

Function # 2 - does not work as expected

Take a string and put it in a StringContent object. This has the side effect of changing the type of content.

  static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(restURLBase); client.DefaultRequestHeaders.Add("Auth-Token", AuthToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent content = new StringContent(postBody); var response = client.PostAsync(RESTUrl, content).Result; // Blocking call! if (!response.IsSuccessStatusCode) { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); return; } } 

Exit # 2

Content type is incorrect when using StringContent + PostAsync

 POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1 Auth-Token: ---- REDACTED ------- Accept: application/json // CORRECT Content-Type: text/plain; charset=utf-8 // WRONG!!! Host: api.dynect.net Content-Length: 100 Expect: 100-continue {"rdata" : ["rname" : "dynect.nfp.com", "zone" : "ABCqqqqqqqqqqqqYYYYYtes3ss.com"], "ttl" : "43200"} // ^^ THIS IS CORRECT 

Function No. 3 - does not work as expected

Since I know that PostAsJsonAsync sets contentType correctly, use this method. (does not work)

  static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(restURLBase); client.DefaultRequestHeaders.Add("Auth-Token", AuthToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent content = new StringContent(postBody); var response = client.PostAsJsonAsync(RESTUrl, content).Result; // Blocking call! if (!response.IsSuccessStatusCode) { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); return; } } 

Exit number 3

Content type is correct, POST body is incorrect when using StringContent + PostAsJsonAsync

 POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1 Auth-Token: -- REDACTED --- Accept: application/json Content-Type: application/json; charset=utf-8 Host: api.dynect.net Content-Length: 74 Expect: 100-continue {"Headers":[{"Key":"Content-Type","Value":["text/plain; charset=utf-8"]}]} 

Question

All I want to do is send JSON as a string or a dynamic object defined at runtime to a server with the correct HTTP content type and a special Auth-Token header.

Any example, if you do not use WebAPI, for example servicestack or something else, is cool.

+7
json c # rest asp.net-web-api
source share
2 answers
 /// <summary> /// Creates a new instance of the <see cref="T:System.Net.Http.StringContent"/> class. /// </summary> /// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StringContent"/>.</param><param name="encoding">The encoding to use for the content.</param><param name="mediaType">The media type to use for the content.</param> [__DynamicallyInvokable] public StringContent(string content, Encoding encoding, string mediaType) : base(StringContent.GetContentByteArray(content, encoding)) { this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "text/plain" : mediaType) { CharSet = encoding == null ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName }; } 

Constructor StringContent. It looks like you should specify the appropriate encodings and mediaType

+6
source share

You cannot directly configure an HttpContent instance because it is an abstract class. You need to use one of the subclasses, depending on your needs. Most likely StringContent, which allows you to set the response string value, encoding and media type in the constructor: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

Answer from How to configure HttpContent for the second HttpClient PostAsync parameter?

+2
source share

All Articles