Reputation: 771
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:
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
Reputation: 2920
Three options:
GetOmnisJson(Stream json)
to GetOmnisJson(YourPeopleClass person)
"Content-Type": "application/json"
in the header (not always an option as other people are consuming the service and you want to behave properly)Upvotes: 4