jQuery ajax跨域调用WCF服务

以下是契约层接口:

namespace Valor.ValorCom.Contracts
{
     [ServiceContract(Name = "NAVService", Namespace = "www.valorcomm.com")]
     public interface INAVService
     {
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <returns></returns>
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string AddOrderForNAV(int orderId);
     }
}

第一点要注意的:指定服务可以通过GET方式调用,设置请求和响应的格式都是JSON.

以下是服务类:

namespace Valor.ValorCom.Services
{
    [AspNetCompatibilityRequirements(
       RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
    public class NAVService : INAVService
    {
        public NAVService()
        {
        }
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <returns></returns>
        public string AddOrderForNAV(int orderId)
        {
            string result = "";
            if (Common.TurnNav())
            {
                //添加订单相关代码
            }
            else
            {
                result = "未开启与NAV系统同步订单的接口";
            }
            return result;
        }
    }
}

第二点要注意的,一定要加上[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")],为javascript回调使用,UrlParameterName 设置用于跨域脚本访问的 URL 查询字符串参数名称。[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 用于asp.net管道兼容,这样的话此服务可以通过jquery ajax跨域调用,asp.net程序也可以通过生成此服务的代理来调用.

 

以下是配置文件信息

<?xml version="1.0"?>
<configuration>
	<system.web>
		<compilation debug="true"/>
	</system.web>
	<appSettings>
	</appSettings>
	<system.serviceModel>
		<behaviors>
			<endpointBehaviors>
				<behavior name="webBehavior">
					<!--这里必须设置-->
					<!--<webHttp />-->
					<enableWebScript />
				</behavior>
			</endpointBehaviors>
			<serviceBehaviors>
				<behavior name="navMetadataBehavior">
					<serviceMetadata httpGetEnabled="true" httpGetUrl="http://wcf.9valor.com/NAVService.svc/metadata"/>
				</behavior>
			</serviceBehaviors>
		</behaviors>
		<services>
			<service behaviorConfiguration="navMetadataBehavior" name="Valor.ValorCom.Services.NAVService">
				<endpoint binding="webHttpBinding" address="http://127.0.0.1:90/NAVService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Valor.ValorCom.Contracts.INAVService" />
				<endpoint address="http://127.0.0.1:90/NAVService" binding="basicHttpBinding" contract="Valor.ValorCom.Contracts.INAVService"></endpoint>
			</service>
		</services>
		<bindings>
			<webHttpBinding>
				<binding name="webBinding" crossDomainScriptAccessEnabled="true">
				</binding>
			</webHttpBinding>
		</bindings>
		<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true">
			<baseAddressPrefixFilters>
				<add prefix="string"/>
			</baseAddressPrefixFilters>
		</serviceHostingEnvironment>
	</system.serviceModel>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
	</startup>
</configuration>

第三点注意:

<service behaviorConfiguration="navMetadataBehavior" name="Valor.ValorCom.Services.NAVService">
				<endpoint binding="webHttpBinding" address="http://127.0.0.1:90/NAVService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Valor.ValorCom.Contracts.INAVService" />
				<endpoint address="http://127.0.0.1:90/NAVService" binding="basicHttpBinding" contract="Valor.ValorCom.Contracts.INAVService"></endpoint>
			</service>

这里配置了两上终结点,第一个终结点的配置给jquery ajax以web的形式调用该服务,指定该终结点的绑定为webHttpBinding,我们看下behaviorConfiguration的配置,

behaviorConfiguration="webBehavior",如下图配置,<enableWebScript /> 配置指定允许web脚本访问。

<endpointBehaviors>
        <behavior name="webBehavior">
          <!--这里必须设置-->
          <!--<webHttp />-->
          <enableWebScript />
        </behavior>
</endpointBehaviors>

接下来我们再看下bindingConfiguration的配置,bindingConfiguration="webBinding",详细配置如下图,crossDomainScriptAccessEnabled指定脚本可以跨域访问.

<webHttpBinding>
        <binding name="webBinding" crossDomainScriptAccessEnabled="true">
        </binding>
</webHttpBinding>

第二个终结点的配置提供给asp.net通过服务代理的方式调用.

 

最后就是客户端调用(注:GET方式在各浏览器下都正常,POST方式只有在IE下能通过,其它浏览器因为安全原因拒绝跨域POST提交)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnExcute").click(function () {
                var url = $("#txtServiceUrl").val();
                url += "&orderId="+$("#txtOrderId").val();
                $.ajax({
                    type: "get",
                    dataType: "json",
                    url: url,
                    success: function (returndata) {
                        alert(returndata);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h2>
        修改单个产品
    </h2>
    <p>
        Wcf Service Url:<input type="text" style=" 700px;" id="txtServiceUrl" name="txtServiceUrl"
            value="http://127.0.0.1:90/AspNavService/web/AddOrderForNAV?jsoncallback=?" />
    </p>
    <p>
        Order Id:<input type="text" id="txtOrderId" name="txtOrderId" value="11665369" />
        <br />
        <input type="button" id="btnExcute" name="btnExcute" value="修改" />
    </p>
</body>
</html>

源码下载:https://files.cnblogs.com/yangbingqi/Valorcom.rar

原文地址:https://www.cnblogs.com/yangbingqi/p/2096197.html