WCF restful WebMessageFormat.Json

时间:2014-01-09 16:14:37

标签: c# json wcf

我有问题。这里是简单的WCF restful服务,虽然我指定了ResponseFormat = WebMessageFormat.Json,但他不想用JSON格式进行响应。他总是使用XMLformat响应:xmlns="http://schemas.datacontract.org/2004/07/GoalTracker.WcfRestService"

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        Database.SetInitializer<GoalTrackerDb>(new GoalTrackerInitializer());
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1)));
    }
}    

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(UriTemplate = "TestPatient",
        ResponseFormat = WebMessageFormat.Json,
        Method = "GET")]
    List<Patient> GetCollection();

    [OperationContract]
    [WebInvoke(UriTemplate = "TestPatient/{id}",
        ResponseFormat = WebMessageFormat.Json,
        Method = "GET")]
    TestPatient Get(string id);
}


[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1 : IService1
{
        GoalTrackerDb db = new GoalTrackerDb();
        public List<Patient> GetCollection()
        {
            var result = db.Patients.ToList();
            return result;
        }
        public TestPatient Get(string id)
        {
            TestPatient testpat = new TestPatient();
            return testpat;
        }
  }

public class TestPatient
{

    public long ID { get; set; }

    public string Email { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public ICollection<TestGoal> Goals { get; set; }

    public TestPatient()
    {
        ID = 0;
        Email = "ads@mail.com";
        FirstName = "janmbo";
        LastName = "Ayo";
        Goals = new Collection<TestGoal>();
        Goals.Add(new TestGoal());
        Goals.Add(new TestGoal());
    }
}


public class TestGoal
{

    public long ID { get; set; }

    public string GoalName { get; set; }

    public TestGoal()
    {
        ID = 2;
        GoalName = "SomeGoalName";
    }
}

1 个答案:

答案 0 :(得分:0)

这很可能是因为误导WebHttpEndpoint.AutomaticFormatSelectionEnabled属性:

  

启用自动格式选择后,WCF基础结构会解析请求消息的接受标头,并确定最合适的响应格式。如果Accept标头未指定合适的响应格式,则WCF基础结构使用请求消息的 Content-Type 或操作的默认响应格式。

因此,如果您使用Accept: application/xml或类似服务来调用此服务,则WebMessageFormat.Json将被默默忽略。您可以在system.serviceModel部分中进行设置:

<standardEndpoints>
   <webHttpEndpoint>
      <standardEndpoint automaticFormatSelectionEnabled="false" />
   </webHttpEndpoint>
</standardEndpoints>
相关问题