wcf - RESTful WCF 用方法名称包装 json 响应

标签 wcf json wcf-rest

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

这是我的操作契约(Contract):

[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 中。现在在 Debug模式下,如果我强行删除这个 FetchStudentsResult 包装,我的反序列化工作得很好。

我试过 DataContractJsonSerializer 但结果完全一样。有人能告诉我我错过了什么吗?

最佳答案

好吧,我自己想通了。问题是以下行:

BodyStyle = WebMessageBodyStyle.Wrapped

当我将其更改为:
BodyStyle = WebMessageBodyStyle.Bare

一切正常!

谢谢!

关于wcf - RESTful WCF 用方法名称包装 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312752/

相关文章:

javascript - jquery 每个 json 对象不执行任何操作

wcf - wcf Restful 服务的命名空间问题

从 C 代码调用 WCF

wcf - Azure辅助角色中的外部HTTP端点可以吗?

c# - 需要避免数字签名公共(public)证书 BinarySecurityElement 被 mtom 编码

javascript - 如何将变量从 JSON 传递到原始 Javascript?

ruby - 减少 RSpec 中 JSON 测试输入的重复

c# - RESTful 服务是否可以从客户端的 "Accept"属性设置其请求和响应类型

c# - 使用动态返回的列绑定(bind)列表

c# - 从哪里开始使用 WCF 和 wsdl 文件?