【问题标题】:ASP.NET Web Application REST JSON always null, even when accepting safelyASP.NET Web 应用程序 REST JSON 始终为空,即使在安全接受时也是如此
【发布时间】: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


【解决方案1】:

终于让它使用了一些我从未想过的最奇怪的语法。 ASP.NET API 为我们做了这么多疯狂的工作,但它并不一定很方便......

public void EditTutorial(String ind, String str)

这行得通,够疯狂的,所以每个键都可以是一个参数。如果我们有一个巨大的 Json 对象,这将是非常低效的,因为函数签名将与相关键一样大,但我将应用它的工作应用程序应该只需要 4-6 个键,所以这就足够了。我希望有一种方法可以直接访问 Json,或者至少访问 API 正在创建的副本而无需使用参数。

【讨论】:

  • 我只使用 Web API 完成了此操作,并且那里的模型绑定器确实会自动将 json 反序列化为像您的“PutData”这样的对象。换句话说,我要写的通常看起来像你原来的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
相关资源
最近更新 更多