Sto tentando di inviare una richiesta POST a un semplice servizio WCF che ho scritto, ma continuo a ricevere 400 richieste non valide. Sto cercando di inviare dati JSON al servizio. Qualcuno può capire cosa sto facendo male? :-)Perché il mio client C#, il POST al servizio WCF REST, restituisce (400) Richiesta errata?
Questa è la mia interfaccia di servizio:
public interface Itestservice
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/create",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
String Create(TestData testData);
}
L'implementazione:
public class testservice: Itestservice
{
public String Create(TestData testData)
{
return "Hello, your test data is " + testData.SomeData;
}
}
Il DataContract:
[DataContract]
public class TestData
{
[DataMember]
public String SomeData { get; set; }
}
E infine il mio codice cliente:
private static void TestCreatePost()
{
Console.WriteLine("testservice.svc/create POST:");
Console.WriteLine("-----------------------");
Uri address = new Uri("http://localhost:" + PORT + "/testweb/testservice.svc/create");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/x-json";
// Create the data we want to send
string data = "{\"SomeData\":\"someTestData\"}";
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
Console.WriteLine();
Console.WriteLine();
}
Qualcuno può pensare a cosa potrei fare di sbagliato? Come potete vedere nel client C# ho provato sia application/x-www-form-urlencoded che text/x-json per ContentType, pensando che potrebbe avere qualcosa a che fare con esso, ma non sembra. Ho provato una versione GET di questo stesso servizio e funziona perfettamente e restituisce una versione JSON di TestData senza problemi. Ma per POST, beh, sto abbastanza bloccato al momento su questo :-(
puoi fornire eventuali registri HTTP (client e/o server)? – defeated