在AngularJs中,我可以通过
轻松地将数据发布到网址$http.post(url, data)
这里的数据是这样的数组:
["test1","test2","test3"]
我的问题是如何在C#中做同样的事情?我想使用 HttpWebRequest 。
答案 0 :(得分:0)
在您的阵列上使用ToList
,在FormUrlEncodedContent
上使用您的帖子请求,请参阅下面的
using System.Net.Http;
data.ToList(); //your data, assuming it is already a well-formed array or data model
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
答案 1 :(得分:0)
其实我自己找到了答案。
这里的有效负载可以是一个数组:
var request =(HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = action;
JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ContractResolver = new UnderscoreMappingResolver(),
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
Converters =
{
new IsoDateTimeConverter
{
DateTimeStyles = DateTimeStyles.RoundtripKind
},
new StringEnumConverter
{
CamelCaseText = true
}
}
};
var json = JsonConvert.SerializeObject(payload, serializerSettings);
request.ContentLength = json.Length;
Console.Out.Write(request.RequestUri);
using (var stream = request.GetRequestStream())
{
using (var sw = new StreamWriter(stream))
{
sw.Write(json);
}
}
HttpWebResponse response;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}