【发布时间】: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 的插件,并告诉我们响应返回的内容(标头信息,例如状态码)