I am trying to return JSON from a WCF Web service but all I get is bad request when I visit the URL.
Here is the interface:
[ServiceContract]
public interface I开发者_如何学运维HighWCFService
{
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "KnownZombies")]
[WebInvoke(Method = "GET")]
List<ZombieInfo> GetZombies();
[OperationContract]
void DoWork();
}
Here is the implementation of the above interface:
public class HighWCFService : IHighWCFService
{
public void DoWork()
{
throw new NotImplementedException();
}
public List<ZombieInfo> GetZombies()
{
var zombies = new List<ZombieInfo>()
{
new ZombieInfo() {FirstName = "John", LastName = "Doe"},
new ZombieInfo() {FirstName = "Mohammad", LastName = "Azam"}
};
return zombies;
}
}
[DataContract]
public class ZombieInfo
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
I visit the following URL which results in 400 bad request:
http://localhost:22059/HighWCFService.svc/KnownZombies
The Web.Config looks like this:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="HighOnCodingWebApps.HighWCFServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="HighOnCodingWebApps.HighWCFServiceBehavior"
name="HighOnCodingWebApps.HighWCFService">
<endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="HighOnCodingWebApps.IHighWCFService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
Two things:
- I think a 400 bad request error is genearated by some other problem not related to JSON.
- I also think that you have to serialize that list in a list of JSON objects in order to receive them since you're not using SOAP anymore. You can use this class DATACONTRACTJSONSERIALIZER
精彩评论