简体   繁体   中英

WCF JSON Service with no DataContract

I'm writing a WCF service where I need to consume a Json message, but I don't want to maintain data contract classes for it. The idea is to consume it via an input stream or string and then serialize it and pass it along to another endpoint. I can read it in, but the input is always null. Maybe there's a way to use a dynamic DataContract that would work, not sure. I can send in a serialized text Json string just fine, but I don't want the customer to just send me the raw json message so I can pass it along serialized to another endpoint. Is this possible w/o the DataContract?

If the message is sent in via application/json, the sMessageIn is always null

[OperationContract]
[WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   BodyStyle = WebMessageBodyStyle.Wrapped,   
   UriTemplate = "/test"
         )]
  String RestMessage(String sMessageIn);

Input Json sent over the wire via Postman using JSON (application/json) mode.

  {
    "test": {
      "Code": "t",
      "Type": "cr"
    }
  }

yes. there is one solution for it. you can use this class as your input and then pass it your dynamic value to it. but unfortunately you cant pass the nested JSON object to it.

[Serializable]
public class WebServiceDictionary : ISerializable
{
    public Dictionary<string, string> Entries { get; }

    public WebServiceDictionary()
    {
        Entries = new Dictionary<string, string>();
    }
    public WebServiceDictionary(SerializationInfo info, StreamingContext context)
    {
        Entries = new Dictionary<string, string>();
        foreach (var entry in info)
            Entries.Add(entry.Name, entry.Value.ToString());
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (var entry in Entries)
            info.AddValue(entry.Key, entry.Value);
    }
}

then you define your method like this:

[OperationContract]
[WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,  
   UriTemplate = "/test"
         )]
  String RestMessage(WebServiceDictionary sMessageIn);

now you can pass any thing you want. some thing like this:

{ "Code": "t", "Type": "cr" }

you can access to the parameters in a Dictionary object like this:

sMessageIn.Entries[Code]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM