【问题标题】:Send data to wcf webservice from jquery从 jquery 向 wcf webservice 发送数据
【发布时间】:2018-08-11 00:04:38
【问题描述】:

我正在尝试使用 jquery 从 html 页面向 wcf webservice 发送 json 字符串。但它给出了错误并且没有返回所需的结果。 html页面显示错误。如何调试服务以查看页面是否实际调用 Web 服务。请帮忙。

IService1.cs

public interface IService1
{

    [OperationContract]
    string GetData(int value);

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}


// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Service1.svc.cs

namespace WcfService2
{

public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}
}

jquery 代码

var markers = [{ "value": "128" }];

    $.ajax({
        type: "POST",
        async: false,
        data: JSON.stringify({ Markers: markers }),
        url: "http://localhost:13008/Service1.svc/GetData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",          
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert("Error");
        }
    });

【问题讨论】:

  • 您的网络服务似乎没有配置为使用或发送 JSON,请尝试删除 contentTypedataType 并将 data 字段设置为 { "value": "128" }。跨度>
  • @Musa 不,它仍然给出错误。
  • var markers = [{ "value": 128 }];怎么样
  • @LeonardoSeccia 不工作
  • 你有没有在端点配置中提到 webhttpbinding

标签: c# jquery ajax wcf


【解决方案1】:

我认为您需要提及 webHttpBinding 来为 restful 服务配置端点。默认情况下,当您在 Visual Studio 中启动服务时,它可能会使用 basicHttpBinding。

您还需要添加属性 [WebInvoke(Method="GET", ResponseFormat=WebMessageFormat.Json,uriTemplate="/json/{id}")] 未在 ide 中签入。但是类似的东西是你需要添加的。

【讨论】:

    【解决方案2】:

    去掉AJAX调用中的数据部分,并在url中传递参数。像这样: http://localhost:13008/service1.svc/GetData?value=128

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2012-10-03
      • 2014-10-12
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      相关资源
      最近更新 更多