1

可能重复:
从 jQuery 调用 Web 服务

我想将两个数字相加,必须在WCF中进行操作,结果会显示在default.aspx页面中。

如何使用 jquery 将两个文本框的值传递给 WCF 服务?

4

1 回答 1

2

您可以从定义一个新的服务合同开始:

namespace WebApplication1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate = "add?a={a}&b={b}", 
                BodyStyle = WebMessageBodyStyle.Bare, 
                ResponseFormat = WebMessageFormat.Json)]
        int Add(int a, int b);
    }
}

一个实现:

namespace WebApplication1
{
    public class Service1 : IService1
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

端点(~/service1.svc):

<%@ ServiceHost 
    Language="C#" 
    Debug="true" 
    Service="WebApplication1.Service1" 
    CodeBehind="Service1.svc.cs" 
%>

并在您的 web.config 中配置服务以启用 REST:

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="">
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="rest">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WebApplication1.Service1">
      <endpoint
        address=""
        contract="WebApplication1.IService1"
        binding="webHttpBinding"
        behaviorConfiguration="rest"
        />
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
</system.serviceModel>

现在您可以将 WebForm1.aspx 添加到您的项目中以使用该服务:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
        $.ajax({
            url: '<%= ResolveUrl("~/service1.svc/add") %>',
            type: 'GET',
            cache: false,
            data: { a: 5, b: 7 },
            success: function (result) {
                alert(result);
            }
        });
    </script>
</body>
</html>
于 2012-10-11T07:24:08.320 回答