我有一个 ASP.NET Web API 操作:
[HttpPost]
public void test(myCustomObj Entity)
{
}
JSON 数据是:
{
"ID": "1",
"Name": "ilhan",
"surname": "aksu"
}
到目前为止,我的代码运行良好。但是,当我添加新的原始参数时:
[HttpPost]
public void test(myCustomObj Entity, [FromBody] string strdata)
{
}
当我发布以下 JSON 时:
{
"Entity": {
"ID": "1",
"Name": "ilhan",
"surname": "aksu"
},
"strdata": "testdata"
}
服务器返回500内部服务器错误。
如何格式化 JSON 数据或更改操作方法来解决此问题?
最佳答案
如果您要发布 json,则可以接受 string
参数:
[HttpPost]
public void Test(string jsonString)
{
}
也许还有一个序列化器帮助程序以避免污染代码:
public static class JsonSerializer
{
public static string Serialize<T>(T t) where T : class
{
return JsonConvert.SerializeObject(t);
}
public static T Deserialize<T>(string s) where T : class
{
return (T)JsonConvert.DeserializeObject(s, typeof(T));
}
}
然后在您的方法中,您可以具体化 json 有效负载:
[HttpPost]
public void Test(string jsonString)
{
var o = JsonSerializer.DeserializeObject(jsonString, typeof(MyObject));
// ...
}
如果您返回 json,则可能如下所示:
[HttpGet]
public JsonResult GetTest()
{
var i = YourService.GetSomethingById(1);
iSerialized = JsonSerializer.Serialize(i);
return new JsonResult
{
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = iSerialized
};
}
关于c# - Web API 一次操作即可完成复杂和原始参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233832/