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)。从那里,您可以开始一次添加您的代码使用的功能,直到您发现它中断的那一刻。这将使您更好地了解出了什么问题。

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 回答