【问题标题】:RESTful WCF wrapping json response with method nameRESTful WCF 使用方法名称包装 json 响应
【发布时间】:2012-03-07 22:30:43
【问题描述】:

我对 RESTful WCF 服务还很陌生,所以请多多包涵。我正在尝试构建一个简单的 RESTful WCF 服务,该服务将学生列表作为 json 响应返回。一切正常,直到我尝试将 json 字符串转换回客户端上的学生对象列表。

这是我的运营合同:

[OperationContract]
[WebGet(UriTemplate = "Students/", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public List<Student> FetchStudents()
{
//Fetch and return students list
}

客户端代码:

static void Main(string[] args)
{
HttpClient client = new HttpClient("http://localhost/StudentManagementService/StudentManagement.svc/");
response = client.Get("Students/");
response.EnsureStatusIsSuccessful();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string str = response.Content.ReadAsString();
List<Student> st = json_serializer.Deserialize<List<Student>>(str);
}

此代码显然失败了,因为服务返回的 json 字符串如下所示:

{"FetchStudentsResult":[{"Course":"BE","Department":"IS","EmailID":"b@gmail.com","ID":1,"Name":"Vinod"}]}

由于某种原因,json 响应被包裹在 FetchStudentsResult 中。现在在调试模式下,如果我强行删除这个 FetchStudentsResult 包装,我的反序列化工作得非常好。

我尝试过 DataContractJsonSerializer,但结果完全一样。谁能告诉我我错过了什么?

【问题讨论】:

    标签: wcf json wcf-rest


    【解决方案1】:

    好的,我自己想通了。问题出在下面一行:

    BodyStyle = WebMessageBodyStyle.Wrapped
    

    当我将其更改为:

    BodyStyle = WebMessageBodyStyle.Bare
    

    一切正常!

    谢谢!

    【讨论】:

    • 感谢 Vinod 您的解决方案帮助了我;你是救生员。
    【解决方案2】:

    就我而言,它是 WebInvoke 而不是 WebGet,我在正文中发送数据。因此,此解决方案对我不起作用。我已经使用了下面的一个,它有效。

    BodyStyle = WebMessageBodyStyle.RequestWrapped
    

    所以在 post 中,body 应该被包裹,但不需要响应。 感谢提问者和他的回答提供了有关此问题的线索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-26
      • 2011-05-30
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 2012-06-15
      • 2012-08-07
      • 2010-10-03
      相关资源
      最近更新 更多