【发布时间】:2016-11-06 16:40:01
【问题描述】:
所以我的 WCF 服务需要能够接收 JSON POST 请求,比如说:
{
"firstname": "Billy",
"lastname": "Jean"
}
带有标题:
"Content-Type": "application/json"
为此,我提出了以下建议。
我的界面:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(UriTemplate = "/PostOmnis",
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
System.Net.HttpStatusCode GetOmnisJson(Stream json);
}
我的班级:
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class Service1 : IService1
{
public class MyMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Raw; // always
}
}
static Binding GetBinding()
{
CustomBinding result = new CustomBinding(new WebHttpBinding());
WebMessageEncodingBindingElement webMEBE = result.Elements.Find<WebMessageEncodingBindingElement>();
webMEBE.ContentTypeMapper = new MyMapper();
return result;
}
public System.Net.HttpStatusCode GetOmnisJson(Stream inputJsonStream)
{
StreamReader reader = new StreamReader(inputJsonStream);
string inputJson = reader.ReadToEnd();
// parse JSON string
.....
...
.
// return HTTP 200
return System.Net.HttpStatusCode.OK;
}
但是,通过Postman 发送一些 JSON,例如:
给我以下错误:
操作“GetOmnisJson”的传入消息(合同“IService1” 带有命名空间 'http://tempuri.org/') 包含无法识别的 http 正文格式值“Json”。预期的正文格式值为“原始”。 这可能是因为尚未配置 WebContentTypeMapper 绑定。有关更多信息,请参阅 WebContentTypeMapper 的文档 详情。
我在这里错过了什么?
【问题讨论】:
-
在标题中发布数据
-
您是指 JSON 请求的标头吗?它已经在那里了,我有截图。
-
您的操作需要一个 Stream,而您正在发布 json 数据,它不会起作用。尝试创建一个与您的 json 数据相同结构的类 (
public class Test { public string firstname { get; set; } .... }) 并更改GetOmnisJson操作以接收此类。
标签: c# json wcf http visual-studio-2015