将JSON数据传递给WCF(.Net 4)Web服务

时间:2011-08-21 21:28:22

标签: wcf json

我有一个非常简单的[OperationContract],名为TestClass,它被调用如下:

var person = { "Name": "Dave", "City":"HB", "State": "CA", "Zip":"92649" };

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(person),                   
                url: "MyService.svc/TestClass",
                success: function (data) {
                    $("#output").text("[ " + data + "]");
                }
            });

我不理解,似乎无法找到,是使用这些服务的首选方式。过去几天我一直在各地寻找,到目前为止,我感到非常不知所措。我读了一篇文章,其中有人说不使用Message但是创建了我自己尝试过的DataContract。

这是我的运营合同:

 [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    public Message TestClass(Message m)
    { return WebOperationContext.Current.CreateTextResponse(JsonConvert.SerializeObject("Ok"));}

除了向TestClass提供4个输入值外,我更喜欢一个。消息是唯一似乎有用的东西。我尝试只使用一个字符串,该值始终为null。

我尝试为数据创建[DataContract]并将其用作TestClass调用中的参数,但也是null。

我是新手使用这些服务类型,所以非常感谢任何初学者的指针。

提前谢谢。

更新

IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfTest
{
    [System.ServiceModel.ServiceContractAttribute()]
    public interface IService
    {
    [System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare, 
     RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, 
     ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]

        [System.ServiceModel.OperationContractAttribute()]
        void ProcessData(RootClass input);
    }

    [System.Runtime.Serialization.DataContractAttribute()]
    public partial class RootClass
    {
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Name;
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string City;
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string State;
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Zip;
    }
}

ServiceZ.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;

namespace WcfTest
{
    public class ServiceZ : IService
    {
        public void ProcessData(RootClass input)
        {
            int i = 6;      // used for a breakpoint
        }
    }
}

的index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="Scripts/json2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $().ready(function () {
            var person = { "Name": "Dave", "City": "HB", "State": "CA", "Zip": "92649" };

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(person),
                url: "ServiceZ.svc/ProcessData",
                success: function (data) {
                    $("#output").text("OK!");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    debugger;
                }
            });
        });
    </script>
</head>
<body>
    <div id="output" style="background: lightgreen;">--></div>
</body>

1 个答案:

答案 0 :(得分:3)

您可以使用数据合同来处理数据。 http://carlosfigueira.me/JsonUtilities/JsonToContract.htm上的工具(有关http://blogs.msdn.com/b/carlosfigueira/archive/2011/01/11/inferring-schemas-for-json.aspx的更多信息)可以为您提供与JSON数据兼容的数据协定。通过输入运行它我得到了下面的代码。

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:v4.0.30319
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[System.ServiceModel.ServiceContractAttribute()]
public interface IService
{
    [System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare, RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    [System.ServiceModel.OperationContractAttribute()]
    void ProcessData(RootClass input);
}

[System.Runtime.Serialization.DataContractAttribute()]
public partial class RootClass
{

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string Name;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string City;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string State;

    [System.Runtime.Serialization.DataMemberAttribute()]
    public string Zip;
}

更新:我创建了一个新项目(空Web应用程序),并添加了以下文件 - 客户端收到了正确的响应。如果有什么不同,请尝试与您所看到的内容进行比较。您获得的415错误通常表明您在此端点上没有适当的绑定/行为。要启用REST端点(可以接受JSON),端点需要具有webHttpBinding以及带有<webHttp/>的行为。或者另一种替代方法(我使用的方法)是在.svc文件上使用WebServiceHostFactory,在这种情况下,你在web.config上不需要任何东西。

<强> ServiceZ.svc

<%@ ServiceHost Language="C#" Debug="true"
    Service="StackOverflow_7141298.ServiceZ"
    CodeBehind="ServiceZ.svc.cs"
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

<强> IServiceZ.cs

namespace StackOverflow_7141298
{
    [System.ServiceModel.ServiceContractAttribute()]
    public interface IService
    {
        [System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare, RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
        [System.ServiceModel.OperationContractAttribute()]
        string ProcessData(RootClass input);
    }

    [System.Runtime.Serialization.DataContractAttribute()]
    public partial class RootClass
    {

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Name;

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string City;

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string State;

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Zip;
    }
}

<强> ServiceZ.svc.cs

namespace StackOverflow_7141298
{
    public class ServiceZ : IService
    {
        public string ProcessData(RootClass input)
        {
            if (input == null) return "NULL!!!";
            StringBuilder sb = new StringBuilder();
            return string.Format("Name={0},City={1},State={2},Zip={3}",
                input.Name ?? "<<null>>",
                input.City ?? "<<null>>",
                input.State ?? "<<null>>",
                input.Zip ?? "<<null>>");
        }
    }
}

<强> HTMLPage1.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="json2.js"></script>
    <script type="text/javascript">
        $().ready(function () {
            var person = { "Name": "Dave", "City": "HB", "State": "CA", "Zip": "92649" };

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(person),
                url: "ServiceZ.svc/ProcessData",
                success: function (data) {
                    $("#output").text(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //debugger;
                    $("#output").text("Error!");
                }
            });
        });
    </script>
</head>
<body>
    <div id="output"></div>
</body>
</html>