我正在尝试构建一个基于 REST 和 json 的 WCF 服务,该服务采用复杂类型作为输入。在客户端上,我尝试使用作为 WCF REST Starter Kit 的一部分的 HttpClient 使用此服务。
下面是我的服务代码:
[WebInvoke(Method = "POST", UriTemplate = "/SendData", BodyStyle = WebMessageBodyStyle.Wrapped)]
public void SendData(List<EditorData> input)
{
//Do something
}
我使用了 WebMessageBodyStyle 枚举中可以找到的其他选项,但没有效果。
这是我也在客户端中使用的复杂类型数据契约:
public class EditorData
{
public string key { get; set; }
public long quesno { get; set; }
public string quescontent { get; set; }
}
客户端代码:
List<EditorData> listEditor = new List<EditorData> { new EditorData { key = "key1", quescontent = "qcontent1", quesno = 1},new EditorData { key = "key2", quescontent = "qcontent2", quesno = 2}};
string jsonEditorList = listEditor.ToJSON();
HttpClient client = new HttpClient("http://localhost/RestWcfService/RestService.svc/");
client.DefaultHeaders.Accept.Add("application/json");
HttpResponseMessage response = null;
response = client.Post("SendData", HttpContent.Create(jsonEditorList));
response.EnsureStatusIsSuccessful();
为了将我的自定义对象列表转换为 json 字符串,我使用了我找到的扩展方法 here
当我运行此应用程序时,出现以下错误:
BadRequest (400) is not one of the following: OK (200), Created (201), Accepted (202), NonAuthoritativeInformation (203), NoContent (204), ResetContent (205), PartialContent (206)
有什么想法吗?
编辑:
这是 fiddle 手屏幕截图:
更新:
根据 Jason Freitas 的建议,我检查了 fiddler 中的响应。内容是这样的:
The server encountered an error processing the request. See server logs for more details.
所以我进入了 IIS 日志,这是 IIS 中记录的错误:
2012-02-15 13:20:08 fe80::ecdd:d2dd:7f70:bef6%11 POST /RestWcfService/RestService.svc/SendData - 80 - fe80::ecdd:d2dd:7f70:bef6%11 - 400 0 0 0
更新2
根据 Rajesh 的建议,我启用了 wcf 服务的跟踪。下面是服务器抛出的异常:
The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.
当我将内容类型指定为 json 时,我仍然不明白它是如何获取原始格式的。
最佳答案
首先尝试启用Tracing在您的 WCF 服务上查看 400 bad request 错误的确切原因。
似乎发布的输入格式错误。您已将 EditorData 列表定义为该方法的参数,并发布一些键值对(引用您的 fiddler 屏幕截图)确保反序列化时 fiddler 中的 json 字符串转换为 EditorData 对象列表。
您还设置了要包裹的主体样式。尝试删除它,看看它是否有效。当您有多个参数时,将使用包装请求,在这种情况下,您将所有参数包装在方法名称元素内并通过网络发送。
更新:
请确保将 Content-Type 添加到 header ,如下所示:
client.DefaultHeaders.ContentType = "application/json";
关于wcf - 错误请求 : WCF REST Service with Starter Kit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9288729/