I am new in wcf restful service. I couldn’t find the problem which was, why my wcf restful service give ‘bad request’. I use .NET 4.0.
My service is:
The way you'll find out the issue with your code is to enable tracing on the server, and it will have an exception explaining the problem. I wrote a simple test with your code, and it had a similar error (400), and the traces had the following error:
The data contract type 'WcfForums.StackOverflow_7058942+Number' cannot be
deserialized because the required data members '<Number1>k__BackingField,
<Number2>k__BackingField' were not found.
Data types marked with [Serializable]
serialize all the fields in the object, not properties. By commenting out that attribute, the code actually works out fine (the type then falls into the "POCO" (Plain Old Clr Object) rule, which serializes all public fields and properties.
public class StackOverflow_7058942
{
//[Serializable]
public class Number
{
public int Number1 { get; set; }
public int Number2 { get; set; }
}
[ServiceContract]
public class Service
{
[OperationContract(Name = "Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public int Add(Number n1)
{
int res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
return res;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
c.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
c.Encoding = Encoding.UTF8;
Console.WriteLine(c.UploadString(baseAddress + "/test/", "{\"Number1\":\"7\",\"Number2\":\"7\"}"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}