C# JSON序列化在WCF Rest服务中不起作用
我正在尝试使用WCF实现基本的rest服务,我遇到了JSON序列化的问题。在我的服务界面中,我定义了下一个方法:C# JSON序列化在WCF Rest服务中不起作用,c#,wcf,rest,service,web,C#,Wcf,Rest,Service,Web,我正在尝试使用WCF实现基本的rest服务,我遇到了JSON序列化的问题。在我的服务界面中,我定义了下一个方法: [OperationContract] [WebGet(UriTemplate = "Book/{id}", ResponseFormat=WebMessageFormat.Xml)] Book GetBookById(string id); 当我使用WebMessageFormat.Xml时,一切正常,但当我将响应格式更改为JSON时,我什么也得不到(只是空的html页面) 我不
[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");
}
}
}
JSON不是HTML。若将JSON输入HTML呈现程序,它将不会在屏幕上呈现任何内容。使用HTTP请求嗅探器(如Fiddler)以其本机编码查看响应。您也可以尝试在浏览器中查看页面源。或许可以帮助您: 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 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
}
}
我试图在我的浏览器中查看页面源代码,但当我使用JSON序列化时,我得到的只是空页面。当我使用Fiddler Web调试器时,我也没有得到响应如果您在URL中使用localhost(服务器和客户端在同一台机器上),请将localhost更改为机器的网络IP地址。Fiddler无法代理localhost连接,因为localhost为网络堆栈设置快捷方式。是的,我有相同的实现[ServiceContract]公共接口IBMooksService{[OperationContract][WebGet(UriTemplate=“Book/{id}”,ResponseFormat=WebMessageFormat.Json)]Book GetBookById(string id);}将该属性移动到接口不会改变任何东西。是否可能传递了错误的图书id,而方法返回null?不,它被排除在外。我刚刚测试了它1秒agoCan您可以使用REST客户机,比如chrome或firefox的fiddler或插件,让我们了解响应返回的内容(头信息,如状态代码)