WCF跨域调用

1  WCf跨域调用  一个用 Jsonp  (这是蒋金楠大神写的一个实例这里把他拷贝过来)(自托管承载)

在契约中

    [ServiceContract]
    public interface IEmployees
    {
        [WebGet(UriTemplate = "all",ResponseFormat =WebMessageFormat.Json)]      
        IEnumerable<Employee> GetAll();
    }
    public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public string Grade { get; set; }
    }



2 在实现类中


   public class EmployeesService : IEmployees
    {
        public IEnumerable<Employee> GetAll()
        {
            return new List<Employee>
            {
                new Employee{ Id = "001", Name="张三", Department="开发部", Grade = "G6"},    
                new Employee{ Id = "002", Name="李四", Department="人事部", Grade = "G7"}, 
                new Employee{ Id = "003", Name="王五", Department="销售部", Grade = "G8"}
            };
        }
    }


3 配置
  <system.serviceModel>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
    <bindings>
      <webHttpBinding>
        <binding crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <services>      
      <service name="Artech.WcfServices.Service.EmployeesService">
        <endpoint kind="webHttpEndpoint" 
                  address="http://127.0.0.1:3721/employees"
                  contract="Artech.WcfServices.Service.Interface.IEmployees"/>
      </service>
    </services>
  </system.serviceModel>


4 在前台调用的时候
  <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "get",
                url: "http://127.0.0.1:3721/employees/all",
                dataType: "jsonp",
                success: function (employees) {
                    $.each(employees, function (index, value) {
                        var detailUrl = "detail.html?id=" + value.Id;
                        var html = "<tr><td>";
                        html += value.Id + "</td><td>";
                        html += "<a href='" + detailUrl + "'>" + value.Name + "</a></td><td>";
                        html += value.Grade + "</td><td>";
                        html += value.Department + "</td></tr>";
                        $("#employees").append(html);
                    });
                    $("#employees tr:odd").addClass("oddRow");
                }
            });

        });
    </script>

 2  第二张 就是正成的网页异步调用只需要在网页中的后台添加2个指令

 public ActionResult GetTest()
        {
            this.Response.AppendHeader("Access-Control-Allow-Origin", "*");            //JS 跨域访问
            this.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

            return Json(new { name = "dw" },JsonRequestBehavior.AllowGet);      
        }

   function GetList() {

            $.get("http://192.168.2.135:8082/mob/Catalog/GetTest", null, function (ajax) {


                alert(ajax.name);

            }, "json");
        }

第二种WCF跨域调用(IIS承载)

1 在接口中这样定义IService1

   [ServiceContract(ConfigurationName = "WcfService1.IService1")]
    public interface IService1
    {

        [OperationContract]
        [WebGet(UriTemplate="/GetData/{value}")]
        string GetData(string value);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetDataUsingDataContract",BodyStyle=WebMessageBodyStyle.WrappedRequest)]
        CompositeType GetDataUsingDataContract(CompositeType composite);
    }

2 配置文件中(有点冗余,直接copy过来)

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior >
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
          <!--<serviceMetadata httpGetEnabled="true" />-->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!--<ServiceInterpector />-->
        </behavior>

      </serviceBehaviors>
      <!--添加配置:配置缺省值为Json-->
      <endpointBehaviors>
        <behavior name="webHttpEndpoint">
          <webHttp helpEnabled="true" defaultBodyStyle="WrappedRequest" defaultOutgoingResponseFormat="Json" faultExceptionEnabled="true"  automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="WcfService1.Service1" >
        <endpoint behaviorConfiguration="webHttpEndpoint" 
                  binding="webHttpBinding" bindingConfiguration="webBinding"
                  contract="WcfService1.IService1" />

      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webBinding" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="104857600">
          <readerQuotas maxArrayLength="104857600" maxStringContentLength="104857600" maxDepth="100"/>
          <security mode="None" >
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  

3 在实现类中Service1 添加一句跨域语句

 public string GetData(string  value)
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            return string.Format("You entered: {0}", value);
        }

4 在Service1.svc文件的查看标记中

去掉CodeBehind

添加 

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

5 调用

说明:Post 我自己还是没发现跨域访问,(只是写了个验证的)在前面的Post的提交时候用Json格式提交

Post提交

   <script type="text/javascript">

        $.ajaxSetup({ contentType: "application/json" });
        $(function () {
            $.post("/Service1.svc/GetDataUsingDataContract", "{"composite":{"BoolValue":true,"StringValue":"213"}}", function (ajax) {
                var str = JSON.stringify(ajax);//转成Json
                alert(str)

            }, "json")
        })

    </script>

Get 提交时可以跨域的

   <script type="text/javascript">
        $(function () {
            $.get("http://localhost:34961/Service1.svc/GetData/{VALUE}", "", function (ajax) { alert(ajax) }, "json")
        })
    </script>

  

 

5

原文地址:https://www.cnblogs.com/cdaq/p/4941867.html