希望这可以帮助。
查看不同的评论和其他论坛,我混合了一些片段,对我来说,这段代码有效......
...在控制器中
public HttpResponseMessage Post([FromBody] string jsonData)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, jsonData);
try
{
string jsonString = jsonData.ToString();
JArray jsonVal = JArray.Parse(jsonString) as JArray;
dynamic mylist= jsonVal;
foreach (dynamic myitem in mylist)
{
string strClave=string.Empty;
string strNum=string.Empty;
string strStatus=string.Empty;
strClave = myitem.clave;
strNum=myitem.num;
strStatus = myitem.status;
}
...在 WebApiConfig.cs 中包含这一行以避免 [FromBody] 变量中的空值var jsonFormatter = config.Formatters.OfType().First();
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); /*this line makes no more null when use [FromBody]*/
}
....在客户端,最重要的是在序列化数据之前连接等号( string json = "=" + SerialData; )
对于我正在使用的序列化
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in DsCnx.Tables[0].Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in DsCnx.Tables[0].Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
SerialData= serializer.Serialize(rows);
PostRequest("http://localhost:53922/api/Demo", SerialData);
这是我的 PostRequest 函数,这里我使用的内容类型是httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; :
private static string PostRequest(string url, string SerialData)
{
string result = String.Empty;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "=" + SerialData;
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (httpWebRequest.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (var errorResponse = (HttpWebResponse)e.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
result = error;
}
}
}
}
return result.ToString();
}
这是我找到一个供参考的代码示例的链接:
https://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing#jobject-and-jarray-in-aspnet-web-api
https://blog.codenamed.nl/2015/05/12/why-your-frombody-parameter-is-always-null/