来自代码的呼叫服务&脚本(相同/不同的域)

时间:2014-08-20 09:46:15

标签: wcf

有人可以在C#中提供WCF服务的示例,可以从代码隐藏,客户端脚本(同一域和不同域)调用

1 个答案:

答案 0 :(得分:1)

我将举例说明一个简单的服务,它将有2个操作合同。

我的服务合同

using System.ServiceModel;
using System.ServiceModel.Web;

namespace Sum_WcfService
{
[ServiceContract(Namespace = "JsonpAjaxService")]
public interface IService1
{
    // Default method for WebInvoke is "POST", cross domain requests are made on GET method
    // I will Invoke this operation on post request
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json)]
    int AddNums(int Num1, int Num2);

    // I will Invoke this operation on get request, from different domain
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string ReturnNum(int Num);
}
}

服务实施

using System.ServiceModel.Activation;

namespace Sum_WcfService
{
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public int AddNums(int Num1, int Num2)
    {
        return Num1 + Num2;
    }
    public string ReturnNum(int Num)
    {
        return "Hey, You called ReturnNum with:" + Num;
    }
}
}

要使服务可以从不同的域调用,请按如下方式添加Factory属性:

<%@ ServiceHost Language="C#" Debug="true" Service="Sum_WcfService.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

现在有服务项目的配置

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>

<system.serviceModel>  

<!--To make service callable from code behind & script as well-->
<client>
<endpoint address="http://localhost/Sum_Wcf/Service1.svc" binding="webHttpBinding"
behaviorConfiguration="EndPointBehavior" contract="SumServiceReference.IService1" name="WebHttpBinding_Well" />
</client>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>

<!--Calling from different domain -->
  <standardEndpoints>
  <webScriptEndpoint>
    <standardEndpoint name="" crossDomainScriptAccessEnabled="true">
  </standardEndpoint>
  </webScriptEndpoint>
</standardEndpoints>

<behaviors>
  <endpointBehaviors>
    <behavior name="EndPointBehavior">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>
</behaviors>

  </system.serviceModel>

 <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>

 </configuration>

现在为您的项目添加一个空的webform,以测试您的服务

在aspx页面中添加以下代码,包含一个jquery文件。

 <script type="text/javascript">
    $(document).ready(
        var Num1 = 10;
        var Num2 = 20;

        $.ajax({
            type: "POST",
            url: 'Service1.svc/AddNums',

            contentType: "application/json; charset=utf-8",
            data: '{"Num1": "' + Num1 +'"' +',' + '"Num2": "' + Num2 + '"}',
            dataType: "json",
            processData: false,
            success: function (data) {
                alert("success:" + data.d);
            },
            error: function (result) {
                alert("error: " + result);
            }
        })
    );

这是您可以从同一个域客户端脚本调用的方法。

现在要从代码后面调用,你需要创建服务的代理类。添加服务引用。 我添加了名称为&#34; SumServiceReference&#34;的服务引用。  我的代码如下:

 using System;
 using System.Globalization;
 using Sum_WcfService.SumServiceReference;

 namespace Sum_WcfService
 {
 public partial class AddServiceClient : System.Web.UI.Page
 {
    protected void Page_Load(object sender, EventArgs e)
    {
         var ServiceProxy = new Service1Client();
         var Sum = ServiceProxy.AddNums(43, 37);
         Page.ClientScript.RegisterStartupScript(GetType(), "ShowAlert", "alert(" + Sum + ")",true);
    }

}
}

现在让我们看看如何从跨域脚本调用。创建一个新项目添加一个webform&amp;在它的aspx页面添加以下代码:

 <script type="text/javascript">
    var Num = 7;

    $(document).ready(
        $.ajax({
            type: "GET",
            url: 'http://localhost:50345/Service1.svc/ReturnNum?Num=' + Num,
            dataType: "jsonp",
            processdata: false,
            success: function(data) {
                alert("success:" + data);
            },
            error: function(result) {
                alert("Failed to call service");
            }
        })
    );
  </script>

现在你的新项目的web.config(用于消费wcf服务)应该是:

 <?xml version="1.0" encoding="UTF-8"?>

 <configuration>
 <system.web>
  <compilation debug="true" targetFramework="4.0" />
 </system.web>

 <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>

尝试使用此代码&amp;报告是否面临任何问题。