【问题标题】:Error receiving JSON (POST) via WCF通过 WCF 接收 JSON (POST) 时出错
【发布时间】: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


【解决方案1】:

三个选项:

  1. GetOmnisJson(Stream json) 更改为GetOmnisJson(YourPeopleClass person)
  2. 不要在标头中传递 "Content-Type": "application/json"(并不总是一个选项,因为其他人正在使用该服务并且您希望行为正常)
  3. 继续使用 Stream,并创建一个 RawContentTypeMapper 来捕获内容类型并仍然允许将其视为 Raw。有关如何做到这一点,请参阅我对其他问题的回答:https://stackoverflow.com/a/54954261/631277

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2019-01-06
    • 2018-10-19
    • 2016-10-30
    • 2014-04-23
    • 1970-01-01
    • 2013-02-26
    • 2023-01-30
    相关资源
    最近更新 更多