【问题标题】:Request JSON data in WCF REST Service and call through jQuery在 WCF REST 服务中请求 JSON 数据并通过 jQuery 调用
【发布时间】:2014-06-12 07:10:33
【问题描述】:

我正在开发一个场景,我必须在 xml 文件中插入数据。

以下是我的服务合同:

namespace WcfService1
{   
    [ServiceContract]
    public interface IService1
    {
       [OperationContract]
       [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "PostData")]
       string InsertData(Data data);
    }

    [DataContract]
    public class Data
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Category { get; set; }
        [DataMember]
        public string Mobile { get; set; }
        [DataMember]
        public string Message { get; set; }
    }
}

我的配置文件:

<configuration>
  <appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.serviceModel>
    <bindings>
  <webHttpBinding>
    <binding name="b_WebHttpBinding" closeTimeout="00:01:00"
    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
    maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Buffered"
    useDefaultWebProxy="true" crossDomainScriptAccessEnabled="true">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
        realm="" />
      </security>
    </binding>
  </webHttpBinding>
</bindings>
   <behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp />
   </behavior>
  </endpointBehaviors>
</behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehaviour" name="WcfService1.Service1">
          <endpoint address="WcfServiceAddress" behaviorConfiguration="web" binding="webHttpBinding"
  bindingConfiguration="b_WebHttpBinding" contract="WcfService1.IService1" />
  </service>
    </services>
    <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

我通过 jQuery 调用它:

$(document).ready(function () {
        $('#BtnRegister').click(function () {
            debugger;
            var input =
                {
                    data:
                        {
                            Name: document.getElementById("TxtUserName").value,
                            Email: document.getElementById("TxtUserEmail").value,
                            Category: document.getElementById("TxtUserCategory").value,
                            Mobile: document.getElementById("TxtUserMobile").value,
                            Message: document.getElementById("message").value,
                        }
                };
            $.ajax({

                type: "POST",
                url: "http://localhost:22727/Service1.svc/WcfServiceAddress/PostData",
                contentType: "application/json",
                data: JSON.stringify(input),
                success: function (result) {
                    alert("data");
                },
                error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
            });
        });
    });

但是数据没有插入到文件中。

【问题讨论】:

标签: c# jquery json wcf


【解决方案1】:

试试这个

var input = 
{
  Name: document.getElementById("TxtUserName").value,
  Email: document.getElementById("TxtUserEmail").value,
  Category: document.getElementById("TxtUserCategory").value,
  Mobile: document.getElementById("TxtUserMobile").value,
  Message: document.getElementById("message").value,
}

var jsonInput = JSON.stringify(input)

然后在你的 ajax 调用中

  $.ajax({

            type: "POST",
            url: "http://localhost:22727/Service1.svc/WcfServiceAddress/PostData",
            contentType: "application/json",
            data: { data : jsonInput } ,
            success: function (result) {
                alert("data");
            },
            error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); }
        });

另外,在 WCF 中的方法上设置一个断点,看看您的 Data 对象是否真的与您发送的输入正确映射。我认为在您的 WCF 方法中,Data 参数为 null

希望对你有帮助。

【讨论】:

  • 不,还是同样的问题。数据没有保存在文件中,我还在我的服务中的方法中放置了断点。但是调试器不去那里
【解决方案2】:

看看这个

/service1.svc/WcfServiceAddress/help

这将返回 WCF 服务中的方法列表并传递参数

我的服务端点声明

<service behaviorConfiguration="ServiceBehaviour" name="DataService.DataService">
    <endpoint address="web" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="DataService.IDataService"/>
    <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" contract="DataService.IDataService"  />
    <endpoint address="soap" binding="basicHttpBinding" contract="DataService.IDataService"/>
  </service>

【讨论】:

  • 当我尝试了你给定的网址时。浏览器显示 Endpoint not found
  • 尝试帮助命令,如果没有显示任何方法,则删除 behaviorConfiguration 并设置 GET 方法而不是 POST 并检查
  • 我必须从服务和端点地址中删除行为配置?
  • 我关注了您的网址,它显示以下内容:“Sendera:DestinationUnreachableThe message with To 'localhost:22727/Service1.svc/WcfServiceAddress/help' 由于 EndpointDispatcher 的 AddressFilter 不匹配,无法在接收方处理。检查发送方和接收方的 EndpointAddresses 一致。”
  • 我正在分享我的端点设置。请与您的配置相匹配
猜你喜欢
  • 1970-01-01
  • 2014-04-30
  • 2011-10-26
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2012-04-23
相关资源
最近更新 更多