2013-03-20 44 views
0

如何從自託管的WCF 4.5服務中獲取JSON?我使用Fiddler2發送請求與「內容類型:應用程序/ JSON」(也嘗試過「內容類型:應用程序/ JavaScript」),但我不斷收到XML。從自託管的WCF 4.5服務返回JSON?

在結合設置「AutomaticFormatSelectionEnabled =真正的」我的WebHttpBehavior我仍然得到XML和使用時,「內容類型:應用程序/ JSON」的服務器將不響應(然後我得到錯誤103)

我在WebHttpBinding上啓用了CrossDomainScriptAccessEnabled,並在控制檯主機中使用WebServiceHost。

的服務很簡單:

[ServiceContract] 
public interface IWebApp 
{ 
    [OperationContract, WebGet(UriTemplate = "/notes/{id}")] 
    Note GetNoteById(string id); 
} 

我也試着設置AutomaticFormatSelectionEnabled爲假,在我的服務合同使用ResponseFormat = WebMessageFormat.Json但也導致「錯誤103」,沒有進一步信息。

我轉身的customErrors並設置FaultExceptionEnabled,HelpEnabled爲true(不知道是否會做任何事情這一點,但只是爲了確保我已經試過了所有)

我失去了一個dll或某物其他?

+0

您是否嘗試過在'WebGet'屬性中設置ResponseFormat = WebMessageFormat.Json屬性? – carlosfigueira 2013-03-20 19:45:58

+0

是的,結果是:「錯誤103(net :: ERR_CONNECTION_ABORTED):未知的錯誤」 – 2013-03-20 20:43:44

+0

另一件嘗試將啓用跟蹤(http://msdn.microsoft.com/en-us/library/ms733025.aspx ),看看是否有什麼可以解釋這個問題。 – carlosfigueira 2013-03-20 21:04:57

回答

5

嘗試開始簡單,如下面的代碼(它適用於4.5)。從那裏,你可以開始一次添加你的代碼使用的功能,直到你找到它的中斷時刻。這會給你一個更好的想法是什麼問題。

using System; 
using System.Net; 
using System.ServiceModel; 
using System.ServiceModel.Web; 

namespace ConsoleApplication5 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string baseAddress = "http://localhost:8000/Service"; 
      WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
      host.Open(); 
      Console.WriteLine("Host opened"); 

      WebClient c = new WebClient(); 
      Console.WriteLine(c.DownloadString(baseAddress + "/notes/a1b2")); 

      Console.WriteLine("Press ENTER to close"); 
      Console.ReadLine(); 
      host.Close(); 
     } 
    } 

    public class Note 
    { 
     public string Id { get; set; } 
     public string Title { get; set; } 
     public string Contents { get; set; } 
    } 

    [ServiceContract] 
    public interface IWebApp 
    { 
     [OperationContract, WebGet(UriTemplate = "/notes/{id}", ResponseFormat = WebMessageFormat.Json)] 
     Note GetNoteById(string id); 
    } 

    public class Service : IWebApp 
    { 
     public Note GetNoteById(string id) 
     { 
      return new Note 
      { 
       Id = id, 
       Title = "Shopping list", 
       Contents = "Buy milk, bread, eggs, fruits" 
      }; 
     } 
    } 
} 
+1

感謝您的推動。你的例子工作正常,所以我試圖讓它越來越像我自己的,看看它打破了什麼地方。我發現問題是我的Note-class中的DateTime屬性被設置爲DateTime.MinValue,這顯然不是由序列化器支持的。什麼是頭腦調試!終於明白了=) – 2013-03-21 16:59:07

+0

我有與DateTime相同的問題。非常感謝,這篇文章節省了我的時間! – 2013-12-23 09:19:11