Search code examples
wcfjsonfiddler

WCF REST POST of JSON: Parameter is empty


Using Fiddler I post a JSON message to my WCF service. The service uses System.ServiceModel.Activation.WebServiceHostFactory

[OperationContract]
[WebInvoke
(UriTemplate = "/authenticate",
       Method = "POST",
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.WrappedRequest
       )]
String Authorise(String usernamePasswordJson);

When the POST is made, I am able to break into the code, but the parameter usernamePasswordJson is null. Why is this?

Note: Strangly when I set the BodyStyle to Bare, the post doesn't even get to the code for me to debug.

Here's the Fiddler Screen: enter image description here


Solution

  • You declared your parameter as type String, so it is expecting a JSON string - and you're passing a JSON object to it.

    To receive that request, you need to have a contract similar to the one below:

    [ServiceContract]
    public interface IMyInterface
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "/authenticate",
               Method = "POST",
               ResponseFormat = WebMessageFormat.Json,
               BodyStyle = WebMessageBodyStyle.Bare)]
        String Authorise(UserNamePassword usernamePassword);
    }
    
    [DataContract]
    public class UserNamePassword
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string Password { get; set; }
    }