【问题标题】:JSON serialization not working in WCF Rest servicesJSON 序列化在 WCF Rest 服务中不起作用
【发布时间】:2013-12-05 17:54:26
【问题描述】:

我正在尝试使用 WCF 实现基本的休息服务,但我遇到了 JSON 序列化的问题。在我的服务接口中,我定义了下一个方法:

[OperationContract]
[WebGet(UriTemplate = "Book/{id}", ResponseFormat=WebMessageFormat.Xml)]
Book GetBookById(string id);

当我使用 WebMessageFormat.Xml 时一切正常,但是当我将响应格式更改为 JSON 时,我什么也得不到(只是空的 html 页面)。

我不知道为什么会这样?我一定是错过了什么。

也许我应该显示我的代码以获取更多详细信息。这是我的服务接口:

[ServiceContract]
    public interface IBookService
    {
        [OperationContract]
        [WebGet(UriTemplate = "Book/{id}", ResponseFormat=WebMessageFormat.Json)]
        Book GetBookById(string id);
    }

这是我的实现:

public class BookService : IBookService
    {
        public Book GetBookById(string id)
        {
            try
            {
                int bookId = Convert.ToInt32(id);

                using (BookContext entities = new BookContext())
                {
                    return entities.BookSet.FirstOrDefault(book => book.Id == bookId);
                }
            }
            catch
            {
                throw new FaultException("Something went wrong");
            }
        }

    }

【问题讨论】:

  • 是否有可能您传递了错误的图书 id 并且您的方法返回 null?
  • 不,它被排除在外。我刚刚在 1 秒前测试过
  • 您能否使用 REST 客户端,例如 fiddler 或 chrome 或 firefox 的插件,并告诉我们响应返回的内容(标头信息,例如状态码)

标签: c# wcf rest service web


【解决方案1】:

JSON 不是 HTML。如果将 JSON 输入 HTML 渲染器,它不会在屏幕上渲染任何内容。使用像 Fiddler 这样的 HTTP 请求嗅探器来查看其本机编码的响应。您也可以尝试在浏览器中查看页面源代码。

【讨论】:

  • 我试图在我的浏览器中查看页面源,但是当我使用 JSON 序列化时,我得到的只是空白页面。
  • 当我使用 Fiddler Web 调试器时,我也没有得到响应
  • 如果您在 URL 中使用 localhost(服务器和客户端在同一台机器上),请将 localhost 更改为机器的网络 IP 地址。 Fiddler 无法代理 localhost 连接,因为 localhost 是网络堆栈的快捷方式。
【解决方案2】:

或许可以帮到你:

json服务合同:

[ServiceContract]
public interface IServiceJson {
    [OperationContract]
    [WebGet(UriTemplate = "Book/{id}", ResponseFormat=WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    Book GetBookById(string id);
}

实施:

public class ServiceImplementation : IServiceJson {
  Book GetBookById(string id) {
    // Implementation
  }
}

【讨论】:

  • 是的,我有同样的实现 [ServiceContract] public interface IBookService { [OperationContract] [WebGet(UriTemplate = "Book/{id}", ResponseFormat=WebMessageFormat.Json)] Book GetBookById(string id ); }
  • 将该属性移动到接口不会改变任何内容。
猜你喜欢
  • 2016-11-16
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多