问题描述
TL; DR-如何将带有auth标头的JSON字符串发送到REST主机?我尝试了3种不同的方法,找到了一种可以处理匿名类型的方法.为什么我不能使用匿名类型?我需要设置一个名为"Group-Name"的变量,并且连字符不是有效的C#标识符.
TL;DR -- How do I send a JSON string to a REST host with an auth header? I've tried 3 different approaches found one that works with anonymous types. Why can't I use anonymous types? I need to set a variable called "Group-Name", and a hyphen isn't a valid C# identifier.
背景
我需要发布JSON,但无法获取正确的正文和内容类型
I need to POST JSON but am unable to get the body and the content type correct
功能#1-适用于匿名类型
内容类型和数据正确,但是我不想使用匿名类型.我想使用一个字符串
The content type and data is correct, but I don't 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;
}
}
输出#1
使用AnonymousTypes + PostAsJsonAsync时,内容类型和数据正确,但是我不想使用匿名类型.
Content type and data is correct when using AnonymousTypes + PostAsJsonAsync, but I don't 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"}
功能2-无法正常工作
取一个字符串并将其放入StringContent对象.这具有更改内容类型的副作用.
Take a string and put it into a StringContent object. This has a side effect of changing the content type.
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;
}
}
输出#2
使用StringContent + PostAsync时内容类型错误
Content type is wrong 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
功能3-不能按预期运行
由于我知道PostAsJsonAsync
正确设置了contentType,因此请使用该方法. (无效)
Since I know PostAsJsonAsync
sets the contentType correctly, lets use that method. (doesn't 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;
}
}
输出#3
内容类型正确,使用StringContent + PostAsJsonAsync时POST正文错误
Content type is correct, POST body is wrong 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"]}]}
问题
我要做的就是将JSON作为字符串或在运行时定义的动态对象发送到服务器,服务器的HTTP内容类型正确,并带有特殊的"Auth-Token"标头.
All I want to do is send JSON as a string, or dynamic object defined at runtime, to a server, with HTTP content type correct, and with a special 'Auth-Token' header.
任何示例,如果不使用WebAPI(例如servicestack)或其他任何很棒的方法.
Any example, if not using WebAPI, such as servicestack, or anything else is cool.
推荐答案
/// <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
};
}
它是StringContent的构造函数.看起来您应该指定适当的Encoding和mediaType
It's constructor of StringContent. Looks like that you should specify appropriate Encoding and mediaType
这篇关于如何将带有自定义标头的任意JSON数据发送到REST服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!