ppp
ppp

Reputation: 771

Error receiving JSON (POST) via WCF

So my WCF service needs to be able to receive a JSON POST request, let's say:

{
    "firstname": "Billy",
    "lastname": "Jean"
}

With headers:

"Content-Type": "application/json"

So to do that, I've come up with the following.

My Interface:

[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);
}

My class:

[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;
    }

However, sending some JSON via Postman such as:

enter image description here enter image description here

Gives me the following error:

Incoming message for operation 'GetOmnisJson' (contract 'IService1' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.

What am I missing here?

Upvotes: 2

Views: 2614

Answers (1)

Matt Kemp
Matt Kemp

Reputation: 2920

Three options:

  1. change GetOmnisJson(Stream json) to GetOmnisJson(YourPeopleClass person)
  2. don't pass the "Content-Type": "application/json" in the header (not always an option as other people are consuming the service and you want to behave properly)
  3. keep using a Stream, and create a RawContentTypeMapper that catches the content-type and still allows it to be treated as Raw. See my answer on this other question for how to do that: https://stackoverflow.com/a/54954261/631277

Upvotes: 4

Related Questions