将JSON发送到WCF Rest Service-对象始终为null [英] Sending JSON to WCF Rest Service - object is always null

查看:89
本文介绍了将JSON发送到WCF Rest Service-对象始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用REST,WCF和JSON(所有这些技术的新功能)使我的应用程序正常工作.我的"GET"工作正常.是导致我出现问题的"POST".

I am trying to get my application working by using REST, WCF and JSON (new to all those technologies). I have the 'GET' working fine. It is the 'POST' that is causing me problems.

您将在下面看到,我使用JSON.stringify打包" JSON,然后将POST启动到REST资源.但是,当对象进入处理请求的WCF方法时,该对象始终为null.

As you will see below I 'pack up' my JSON using JSON.stringify, then fire off the POST to the REST resource. However, when the object gets to the WCF method that is handling the request the object is always null.

这是代码:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "Services/ContactCompanyService.svc/contactcompanies/customers",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ contactcompany: newCustomer }),
    success: function (html) { alert(html); }
});

这是配置文件:

<services>
  <service behaviorConfiguration="ServiceBehaviour" name="ContactCompanyService">
    <endpoint address="contactcompanies" behaviorConfiguration="web" binding="webHttpBinding" contract="IContactCompanyService"/>
  </service>

</services>

<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
      <enableWebScript/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>

这是合同:

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "customers")]
    [return: MessageParameter(Name = "ContactCompany")]
    ContactCompany AddContactCompany(ContactCompany ContactCompanyObject);

这是实现上述接口的方法,其中ContactCompanyObject为null.

And it is the method that implements the above interface where ContactCompanyObject is null.

我到底在做什么错?请不要排除我的愚蠢.

What on earth am I doing wrong? Please don't rule out stupidity on my part.

进一步: 我将WebMessageBodyStyle更改为.Bare,这导致对象不为null ...但该对象的EVERY属性均为null.就是说,包裹是我想走的路.

Further: I changed the WebMessageBodyStyle to .Bare, and this resulted in the object not being null ... but EVERY property of the object being null. That said, wrapped is the way I would like to go.

我将不胜感激.让我知道您是否需要更多信息.

I would be grateful of any assistance. Let me know if you need further information.

更新

我从头开始了一个全新的项目-剥离回来.

I started from scratch with a completely new project - stripped back.

我得到的结果完全相同-WCF代码接收到该对象时,该对象为空.

I am getting exactly the same result - the object, when received by the WCF code, is null.

这就是我在这个新测试项目中所做的.

Here's what I did on this new test project.

WCF合同:

(在命名空间下:NullTestService

(under the namespace: NullTestService

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "NullTestPost")]
    [return: MessageParameter(Name = "NullTestType")]
    NullTestType GettMethod();

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "NullTestPost")]
    [return: MessageParameter(Name = "NullTestType")]
    NullTestType PostMethod(NullTestType NullTestTypeObject);
}

[DataContract]
public class NullTestType
{
    [DataMember]
    public string NullTestString { get; set; }
    [DataMember]
    public int NullTestInt { get; set; }
}

服务实施: (相同的名称空间)

Service Implementation: (same namespace)

    public class Service1 : IService1
{
    public NullTestType PostMethod(NullTestType NullTestTypeObject)
    {
        return NullTestTypeObject;
    }

    public NullTestType GettMethod()
    {
        return new NullTestType { NullTestString = "Returned String", NullTestInt = 25 };
    }

}

网站项目. Service.svc:

Website project. Service.svc:

<%@ ServiceHost Service="NullTestService.Service1" %>

Web项目中的

web.config:

web.config in the web project:

    <system.serviceModel>
<services>
  <service behaviorConfiguration="ServiceBehaviour" name="NullTestService.Service1">
    <endpoint address="nulltestaddress" behaviorConfiguration="web" binding="webHttpBinding" contract="NullTestService.IService1"/>
  </service>

</services>

<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="false" />
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
</system.serviceModel>

最后是Web项目中的jQuery:

and finally the jQuery in the web project:

$(function () {


//        $.ajax({
//            type: "GET",
//            url: "http://localhost:8080/TestWeb/Service.svc/nulltestaddress/nulltestpost",
//            success: alertResult
//        });

alert('about to do it');

$.ajax({
    type: "POST",
    url: "http://localhost:8080/TestWeb/Service.svc/nulltestaddress/nulltestpost",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: '{"NullTestType":{"NullTestString":"This is a post string","NullTestInt":25}}',
    success: alertResult
});

});

function alertResult(data) {
        alert(data.NullTestType.NullTestString);
}

所以. (注释掉)GET可以正常工作并返回JSON. POST不这样做.上线:

So. The (commented out) GET works fine and returns the JSON. The POST does not. On the line:

public NullTestType PostMethod(NullTestType NullTestTypeObject)
{
    return NullTestTypeObject;
}

("return"行)NullTestTypeObject始终为NULL.

(the 'return' line) the NullTestTypeObject is always NULL.

我将非常感谢您的帮助.我为此花了很多时间.

I would be very grateful for help. I have lost a lot of time over this.

推荐答案

如果要包装,则需要将请求包装在操作参数名称中:

If Wrapped is what you want to do, then you need to wrap the request in the operation parameter name:

var input = { "ContactCompanyObject" : newCustomer };
$.ajax({
   data: input
   ...
});

或者在第二个示例中,如果将ajax调用更改为如下所示,则应该获得预期的结果:

Or for the second example, if you change the ajax call to the one shown below, you should get the expected result:

var input = { NullTestTypeObject: { NullTestString: "Hello", NullTestInt: 123} };
alert("Input: " + JSON.stringify(input));
$.ajax({
    type: "POST",
    url: "./Service1.svc/nulltestaddress/NullTestPost",
    contentType: "application/json",
    data: JSON.stringify(input),
    success: function (result) {
        alert("POST result: " + JSON.stringify(result));
    }
});

这篇关于将JSON发送到WCF Rest Service-对象始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆