Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client Website always return Null Json String

I've gotten to a point now where I can receive responses from a client website I've made (for internal use in the company I work at) on my WCF Webservice. But whenever I get a response it's always null.

I've look around for various solutions and none of them seems to fix this issue. I have the following:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/AddNewActivity")]
String AddNewActivity(String jsonObject);

And implemented:

public String AddNewActivity(String jsonObject)
{
    return JsonConvert.SerializeObject("Success");
}

Just to test that it works. I set a breakpoint at the above function to read the jsonObject string and see what it looks like. When I read it though, it's null. Always null.

Here is the JavaScript:

function OnModalCreateNewActivityBtnClick() {
    var modal = $('#new-activity-modal-body');
    var activityMap = {
        status: modal.find('#new-activity-modal-status-dropdown').val(),
        name: modal.find('#new-activity-modal-name-field').val(),
        responsible: modal.find('#new-activity-modal-responsible-field').val(),
        department: modal.find('#new-activity-modal-department-dropdown').val(),
        startTime: modal.find('#new-activity-modal-datepicker-start').val(),
        endTime: modal.find('#new-activity-modal-datepicker-end').val(),
        description: modal.find('#editor').cleanHtml(),
        axAccounts: modal.find('#new-activity-modal-ax-account-numbers-field').val()
    };
    var jsonObject = '{ "String": ' + JSON.stringify(activityMap) + '}';
    $.ajax({
        type: 'POST',
        url: 'http://localhost:52535/PUendeligService.svc/AddNewActivity',
        data: jsonObject,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        processData: true,
        success: function (data, status, jqXHR) {
            alert("Success: " + data);
        },
        error: function (xhr) {
            console.log(xhr.responseText);
            alert("Error: " + xhr.responseText);
        }
    });
}

Anyone have any idea why it returns null?

UPDATE

I used Fiddler and the information that leaves the website to the web service is correct. It's a JSON String that Fiddler can read. But the web service still receives a null object.

like image 357
OmniOwl Avatar asked Jan 21 '16 14:01

OmniOwl


2 Answers

Let's simplify your sample a bit and start with this

<script type="text/javascript">
    function OnModalCreateNewActivityBtnClick() {

        var data = {
            Status: modal.find('#new-activity-modal-status-dropdown').val(),
            Name: modal.find('#new-activity-modal-name-field').val()
        };

        $.ajax({
            type: 'POST',
            url: 'Service.svc/AddNewActivity',
            data: JSON.stringify(data), 
            contentType: 'application/json; charset=utf-8', 
            dataType: 'json', 
            success: function (msg) {
                alert(data.Status + ' == ' + msg.Status);
            },
            error: function (e) {
                alert('failed with ' + e.statusText);
            }
        });
    }
</script>

Your activity class

   [DataContract]
    public class Activity
    {
        [DataMember]
        public String Status
        {
            get; set;
        }

        [DataMember]
        public String Name
        {
            get; set;
        }
    }

Implementation

[WebInvoke(Method ="POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "AddNewActivity/")]
public Activity AddNewActivity(Activity activity)
{
  // your stuff
  return activity;
}

Lastly, since you didn't show your configuration let's assume the following

     <system.serviceModel>
    <services>
      <service name="PUendelig.Service"  behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="PUendelig.IService" behaviorConfiguration="web"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>

    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

I put this together in github for you to download. Please feel free to adjust as need be and help others in the process https://github.com/alexnolasco/SO35094908

like image 121
Alex Nolasco Avatar answered Nov 15 '22 18:11

Alex Nolasco


The error seems to be here:

var jsonObject = '{ "String": ' + JSON.stringify(activityMap) + '}';

Remove that line, as you do not need it and change your AJAX call to the following:

$.ajax({
        type: 'POST',
        url: 'http://localhost:52535/PUendeligService.svc/AddNewActivity',
        data: {jsonObject: JSON.stringify(activityMap) },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        processData: true,
        success: function (data, status, jqXHR) {
            alert("Success: " + data);
        },
        error: function (xhr) {
            console.log(xhr.responseText);
            alert("Error: " + xhr.responseText);
        }
    });

The problem is that your service expects "jsonObject" variable, but you are sending "String". Hope this helps.

like image 2
Roman Hutnyk Avatar answered Nov 15 '22 18:11

Roman Hutnyk