DarkLink February 2016

Deserializing JSON in REST Service

I am having a problem deserializing json in my rest self-hosted service.

I have a test page that invokes the self-hosted REST with JSON, here is the code:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript">
        function doFunction() {

            xhr = new XMLHttpRequest();
            var url = "https://localhost:1234/business/test/testing2/endpoint";
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var json = JSON.parse(xhr.responseText);
                    alert(json);
                }
            }                            
            var data = JSON.stringify({ testing : "test" });
            xhr.send(data);
        }

    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
    </div>
    </form>

</body>
</html>

And here is the interface and contracts of my self-hosted service:

[DataContract]
    public class OperationInput
    {
        [DataMember]
        public string testing { get; set; }

    }

    [DataContract]
    public class OperationOutput
    {
        [DataMember]
        public int Status { get; set; }

        [DataMember]
        public string Message { get; set; }

        [DataMember]
        public string AddInfo { get; set; }

        [DataMember]
        public string PartnerID { get; set; }

        [DataMember]
        public string SessionID { get; set; }
    }

    [ServiceContract]
    interface IRegisterOperation
    {
        [OperationContract]
        [WebInvoke(UriTemplate         

Answers


granadaCoder February 2016

You have Method = "*"

I would experiment with:

Method = "POST" ....

[ServiceContract]
interface IRegisterOperation
{
    OperationOutput Operation(OperationInput order);

like so:

[OperationContract]
[WebInvoke(UriTemplate = "/registeroperation",
       Method = "POST",
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare)]
OperationOutput Operation(OperationInput order);

APPEND:

Your json does not look right (from the screen shots)

I would expect something simple like:

{
    "ACTPRDX": "test"
}

Can you do an "alert" right after you stringify the object? And show the results?

But (in general)...if your json is messed up, the "auto voodoo" of the Wcf Service Method won't work.

.....

This might be nit-picky, but try this:

Note the capital "T" after the hyphen.

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

I just found this in my code:

        var jsonObject = { ACTPRDX : "test" };
        var whatToSendOverTheWire = JSON.stringify(jsonObject);

Try that.

As mentioned, your json is wrong. the fix is to figure out how its being screwed up.


user1075940 February 2016

You actually pass primitive instead of expected object

var data = JSON.stringify({ ACTPRDX : "test" });

The above data would work for method :

   public XYZ Something(string ACTPRDX)

You should send object to your method like that

var obj= new Object();
obj.ACTPRDX = "test";
var data = JSON.stringify({ order: obj});

Also interface and implementation have different name for parameter OperationInput -> order and input.


DarkLink February 2016

I figured it out, the problem was the OPTIONS Request, I need to receive a POST Request so I get the JSON.

I added a behaviour attribute to my service host so that it responds to options request allowing the wcf service host to receive cross origin requests.

So I added the code from the answer of this (Cross Origin Resource Sharing for c# WCF Restful web service hosted as Windows service) question and now I get a POST Request after the first Options request:

If the link is no longer available, here is the solution of the question:

CODE:

Create 2 classes as follows:

  1. MessageInspector implementing IDispatchMessageInspector.
  2. BehaviorAttribute implementing Attribute, IEndpointBehavior and IOperationBehavior.

With the following details:

//MessageInspector Class
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
namespace myCorsService
{
  public class MessageInspector  : IDispatchMessageInspector
  {
    private ServiceEndpoint _serviceEndpoint;

    public MessageInspector(ServiceEndpoint serviceEndpoint)
    {
      _serviceEndpoint = serviceEndpoint;
    }

    /// <summary>
    /// Called when an inbound message been received
    /// </summary>
    /// <param name="request">The request message.</param>
    /// <param name="channel">The incoming channel.</param>
    /// <param name="instanceContext">The current service instance.</param>
    /// <returns>
    /// The object used to correlate stateMsg. 
    /// This object is passed back in the method.
    /// </returns>
    public obj 

Post Status

Asked in February 2016
Viewed 3,142 times
Voted 11
Answered 3 times

Search




Leave an answer