2014-01-09 3 views
0

У меня проблема. Здесь простая служба WCF restful, и он не хочет отвечать в формате JSON, хотя я указываю ResponseFormat = WebMessageFormat.Json. Он всегда ответы с XMLformat: xmlns="http://schemas.datacontract.org/2004/07/GoalTracker.WcfRestService"WCF restful WebMessageFormat.Json

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 = "[email protected]"; 
     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"; 
    } 
} 
+0

Измените его 'WebMessageFormat.Xml' может быть? – Tim

+0

Нет, нужен формат Json – Ark

ответ

0

Это, скорее всего, из-за недостоверной WebHttpEndpoint.AutomaticFormatSelectionEnabled собственности:

Когда автоматический выбор формата включена, WCF инфраструктура разбирает Accept заголовок сообщения запроса и определяет наиболее подходящий формат ответа. Если заголовок Accept не указывает подходящий формат ответа, инфраструктура WCF использует Content-Type сообщения запроса или формат ответа по умолчанию для операции.

Так что, если вы называете эту услугу с Accept: application/xml или подобными, WebMessageFormat.Json будут игнорироваться. Вы можете установить его в system.serviceModel разделе:

<standardEndpoints> 
    <webHttpEndpoint> 
     <standardEndpoint automaticFormatSelectionEnabled="false" /> 
    </webHttpEndpoint> 
</standardEndpoints> 
+0

Спасибо, это помогает! – Ark

Смежные вопросы