jQuery 将 JSON 发送到 WCF 休息服务 - 对象始终为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6049454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:18:16  来源:igfitidea点击:

Sending JSON to WCF Rest Service - object is always null

wcfjsonrestjquery

提问by GrayDS

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.

我正在尝试使用 REST、WCF 和 JSON(所有这些技术都是新的)来让我的应用程序工作。我有 'GET' 工作正常。是“POST”导致我出现问题。

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.

正如您将在下面看到的,我使用 JSON.stringify 来“打包”我的 JSON,然后将 POST 发送到 REST 资源。但是,当对象到达处理请求的 WCF 方法时,该对象始终为空。

Here is the code:

这是代码:

$.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); }
});

Here is the config stuff:

这是配置的东西:

<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"/>

Here is the contract:

这是合同:

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

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

并且是实现上述ContactCompanyObject为null的接口的方法。

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

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

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.

进一步:我将 WebMessageBodyStyle 更改为 .Bare,这导致对象不为空……但对象的每个属性都为空。也就是说,包裹是我想要的方式。

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

如有任何帮助,我将不胜感激。如果您需要更多信息,请告诉我。

UPDATE

更新

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

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

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

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

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

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

WCF Contract:

WCF合约:

(under the namespace: NullTestService

(命名空间下: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 };
    }

}

Website project. Service.svc:

网站项目。服务.svc:

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

web.config in the web project:

web项目中的web.config:

    <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>

and finally the jQuery in the web project:

最后是 web 项目中的 jQuery:

$(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);
}

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

所以。(注释掉的) GET 工作正常并返回 JSON。POST 没有。在线上:

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

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

('return' 行)NullTestTypeObject 始终为 NULL。

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

我将非常感谢您的帮助。我为此失去了很多时间。

采纳答案by carlosfigueira

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

如果 Wrapped 是你想要做的,那么你需要将请求包裹在操作参数名称中:

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

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

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

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));
    }
});