0

セルフホステッド WCF 4.5 サービスから JSON を取得するにはどうすればよいですか?

Fiddler2 を使用して「Content-Type: application/json」(「Content-Type: application/javascript」も試しました) でリクエストを送信していますが、XML を取得し続けています。

WebHttpBehavior で「AutomaticFormatSelectionEnabled = true」を設定することと組み合わせて、XML を取得し、「Content-Type: application/json」を使用すると、サーバーがまったく応答しません (その後、エラー 103 が発生します)。

WebHttpBinding で CrossDomainScriptAccessEnabled を有効にし、コンソール ホストで WebServiceHost を使用しています。

サービスはとてもシンプルです:

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

また、AutomaticFormatSelectionEnabled を false に設定し、サービス コントラクトで ResponseFormat = WebMessageFormat.Json を使用しようとしましたが、「エラー 103」が発生し、それ以上の情報はありません。

customErrors をオフにして、FaultExceptionEnabled、HelpEnabled を true に設定しました (これで何かができるかどうかはわかりませんが、すべて試してみたことを確認するためだけです)。

私はdllか何かを見逃していますか?

4

1 に答える 1

5

以下のコードのように、単純なものから始めてみてください (4.5 で動作します)。そこから、壊れる瞬間が見つかるまで、コードで使用する機能を 1 つずつ追加し始めることができます。これにより、何が問題なのかがよりよくわかります。

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"
            };
        }
    }
}
于 2013-03-20T21:13:20.363 に答える