我是wcf restful service的新手.我找不到问题,为什么我的wcf宁静服务给出"错误的请求".我使用.NET 4.0.
我的服务是:
[OperationContract(Name="Add")] [WebInvoke(UriTemplate = "test/", Method = "POST", ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json )] public int Add(Number n1) { res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2); return res; }
数据是......
[Serializable] public class Number { public int Number1 { get; set; } public int Number2 { get; set; } }
当我从fiddler打电话回来'HTTP/1.1 400 Bad Request'时
我的fiddler请求标题是:
User-Agent: Fiddler Host: localhost:4217 Content-Type: application/json; charset=utf-8
请求正文是:
{"Number1":"7","Number2":"7"}
响应头是:
HTTP/1.1 400 Bad Request Server: ASP.NET Development Server/10.0.0.0 Date: Sun, 14 Aug 2011 18:10:21 GMT X-AspNet-Version: 4.0.30319 Content-Length: 5450 Cache-Control: private Content-Type: text/html Connection: Close
但是,如果我通过C#客户端程序调用此服务,则可以.
我的客户代码是:
uri = "http://localhost:4217/Service1.svc/"; Number obj = new Number() { Number1 = 7, Number2 = 7 }; using (HttpResponseMessage response = new HttpClient().Post(uri+"test/", HttpContentExtensions.CreateDataContract(obj))) { string res = response.Content.ReadAsString(); return res.ToString(); }
请帮我........
谢谢.
您将发现代码问题的方法是在服务器上启用跟踪,并且它将解释该问题.我用你的代码写了一个简单的测试,它有一个类似的错误(400),并且跟踪有以下错误:
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.
标记的数据类型[Serializable]
序列化对象中的所有字段,而不是属性.通过注释掉该属性,代码实际上运行良好(该类型然后属于"POCO"(Plain Old Clr Object)规则,该规则序列化所有公共字段和属性.
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(); } }