使用jQuery AJAX调用WCF服务

时间:2015-02-25 19:02:51

标签: jquery asp.net ajax json wcf

我有以下WCF服务。

接口代码:

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

namespace CalculatorWebService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICalculatorService" in both code and config file together.
    [ServiceContract]
    public interface ICalculatorService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat= WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        int Addition(int firstNumber, int secondNumber);

        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        int Subtraction(int firstNumber, int secondNumber);
    }
}

SVC代码:

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

namespace CalculatorWebService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CalculatorService" in code, svc and config file together.
    public class CalculatorService : ICalculatorService
    {
        public int Addition(int firstNumber, int secondNumber)
        {
            return firstNumber + secondNumber;
        }

        public int Subtraction(int firstNumber, int secondNumber)
        {
            return firstNumber - secondNumber;
        }
    }
}

现在,我有以下HTML页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HomePageWithAjax.aspx.cs" Inherits="CalculatorWebService.HomePageWithAjax" %>

<!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 runat="server">
    <title></title>
    <script src="http://localhost:12345/js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="http://localhost:12345/js/ajaxScript.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <label>Number 1:&nbsp;</label>
        <label ID="labelFirstNumber"></label>
        <br />

        <label>Number 2:&nbsp;</label>
        <label ID="labelSecondNumber"></label>
        <br />
        <br />

        <label>Addition:&nbsp;</label>
        <label ID="labelAddition"></label>
        <br />

        <label>Subtraction:&nbsp;</label>
        <label ID="labelSubtraction"></label>
        <br />
    </div>
    </form>
</body>
</html>

这是调用WCF服务的脚本:

function generateRandomNumber()
{
    var number = Math.floor((Math.random() * 100) + 1);
    return number;
}

function getNumber(labelName) {
    return $(labelName).text();
}

function setNumber(labelName, number)
{
    $(labelName).text(number);
}

function addition() {
    var input = new Object();
    input.firstNumber = getNumber("#labelFirstNumber");
    input.secondNumber = getNumber("#labelSecondNumber");

    $.ajax({
        type: "POST",
        url: "/CalculatorService.svc/Addition",
        data: JSON.stringify(input),
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (result) {
            setNumber("#labelAddition", result);
        },
        error: function (response, status, error) {
            alert(response.statusText);
        }
    });
}

function subtraction() {
    var input = new Object();
    input.firstNumber = getNumber("#labelFirstNumber");
    input.secondNumber = getNumber("#labelSecondNumber");

    $.ajax({
        type: "POST",
        url: "/CalculatorService.svc/Subtraction",
        data: JSON.stringify(input),
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (result) {
            setNumber("#labelSubtraction", result);
        },
        error: function (response, status, error) {
            alert(response.statusText);
        }
    });
}

$(document).ready(function () {
    var firstNumber = generateRandomNumber();
    var secondNumber = generateRandomNumber();

    setNumber("#labelFirstNumber", firstNumber);
    setNumber("#labelSecondNumber", secondNumber);

    addition();
    subtraction();
});

这是 Web.config

<?xml version="1.0"?>
<configuration>

  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="CalculatorWebService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

 <applicationSettings>
  <CalculatorWebService.Properties.Settings>
   <setting name="CalculatorWebService_CalculatorServiceReference_CalculatorService"
    serializeAs="String">
    <value>http://localhost:12345/CalculatorService.svc</value>
   </setting>
  </CalculatorWebService.Properties.Settings>
 </applicationSettings>
</configuration>

现在,由于某种原因,对添加 Web服务方法和减法 Web服务方法的调用都返回以下错误:

Unsupported Media Type

为什么会返回此错误?我认为Web服务应该知道它正在期待JSON,因为:

  1. 我将输入指定为JSON(contentType字段)
  2. 我将输出指定为JSON(dataType字段)
  3. 我在Web服务中将请求和响应类型指定为JSON 接口
  4. 我错过了什么?

    非常感谢。

    注意

    我使用的WCF服务不是支持AJAX的WCF服务。这可能是问题吗?是否可以通过修改Web.config文件使其启用AJAX?

1 个答案:

答案 0 :(得分:1)

您必须将以下属性添加到服务中,以允许通过HTTP管道调用它: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

或在system.serviceModel:

下的配置中

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

然后,您可以在ScriptManager中添加servicereference或像您一样调用代理端点。

如果您无法更改服务或者您在更改服务时遇到问题,可以随时通过使用[WebMethod]修改代码隐藏方法从客户端调用页面方法,然后在那里进行服务调用