【发布时间】:2018-05-12 10:21:29
【问题描述】:
我关注this tutorial 创建一个 RESTful Web 服务应用程序。我只使用简单的字符串通过它的指令成功地创建了 GET、POST 和 DELETE。但是,我现在尝试使用“复杂”类(只有 2 个字符串)自己创建一个 PUT 方法,无论我读了多少关于 null 进入的页面,似乎都没有让它正确。我很确定问题出在我的 JSON 发送端(使用 Postman)而不是我的 RESTful 服务器上,但这是两者的重要部分:
复杂类 (C#)
public class PutData
{
public string ind { get; set; }
public string str { get; set; }
}
PUT 方法 (C#)
[WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Tutorial",
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public void EditTutorial(Object json) //<- have also tried PutData and string
{
var jsonString = json.ToString();// this Object implementation is from another S.O. page
PutData data = JsonConvert.DeserializeObject<PutData>(jsonString);
int pid;
Int32.TryParse(data.ind, out pid);
lst[pid] = data.str;
}
JSON 作为 PUT(邮递员)发送
{ "ind" : "0", "str" : "Dictionary" }
我的 Postman 设置是
正文:原始 JSON(应用程序/json)
内容类型:application/json
有什么想法吗?
【问题讨论】:
-
所以json参数为null,所以第一行报错?
-
在第一行打断点,Object json 为空,尝试一步,它已经抛出了 nullreferenceexception 的函数
-
可能偶然发现了问题或线索。因此,即使我通过 Postman 中标头的键/值将 Content-Type 设置为 application/json,当 Content-Type text/html 失败时,我也会被传回。还是正常的?
-
@NickCondatore 您需要在客户端设置接受标头才能返回 json。
-
@Eris 你能设置吗?在我看来,它是以回复的任何格式返回的,在我设置为 WebMessageFormat.Json 的代码中,但因为它引发了异常,所以它看起来像是获得了具有默认格式的默认回复。
标签: c# asp.net json rest postman