将JSON数据传递到WCF(.Net 4)Web服务 [英] Passing JSON data to WCF (.Net 4) Web Service

查看:86
本文介绍了将JSON数据传递到WCF(.Net 4)Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very simple [OperationContract] called TestClass that gets called like this:

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.

What I'm not understanding, and can't seem to find, is the preferred way of using these services. I've been searching everywhere for the past few days and I feel really overwhelmed with what I've found so far. I read one post where somebody said not to use Message but to create their own DataContract which I tried.

这是我的运营合同:

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

除了有4个输入给TestClass的值外,我更喜欢一个.消息似乎是唯一可行的方法.我尝试仅使用字符串,并且该值始终为null.

Besides having 4 input values to TestClass, I would prefer just one. Message is the only thing that seems to work. I tried using just a string and that value is always null.

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

I've tried creating a [DataContract] for the data and use that as the parameter in the TestClass call but that also is null.

我是使用这些服务类型的新手,因此非常感谢初学者的所有指针.

I'm new to using these service types so any pointers for a beginner is greatly appreciated.

谢谢.

更新

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>

推荐答案

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

You can use a the data contract for your data. The tool at http://carlosfigueira.me/JsonUtilities/JsonToContract.htm (more information about it at http://blogs.msdn.com/b/carlosfigueira/archive/2011/01/11/inferring-schemas-for-json.aspx) can give you a data contract which is compatible with the JSON data. By running it with your input I got the code below.

//------------------------------------------------------------------------------
// <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上放置任何内容.

Update: I created a new project (empty web application), and added the following files - the client received the correct response. Try comparing with what you have to see if there is anything different. And the 415 error you're getting usually indicates which you don't have the appropriate binding / behavior on this endpoint. To enable REST endpoints (which can accept JSON), the endpoint needs to have the webHttpBinding and a behavior with the <webHttp/> on it. Or another alternative (which is what I used) is to use the WebServiceHostFactory on the .svc file, in which case you don't need anything on 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>

这篇关于将JSON数据传递到WCF(.Net 4)Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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