[英]Calling Cross domain WCF Service Using jQuery AJAX with JSON
I am new with WCF and almost try every Web Site to do this task. 我是WCF的新手,几乎可以尝试每个网站来执行此任务。 This Is My Service 这是我的服务
namespace WCFSeviceWebHttpBinding
{
"IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json , UriTemplate="/d")]
[OperationContract]
string DoWork();
}
}
namespace WCFSeviceWebHttpBinding
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string DoWork()
{
return "Hello";
}
}
}
Web.Config Web配置
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
<system.serviceModel>
<services>
<service name="WCFSeviceWebHttpBinding.Service1" behaviorConfiguration="serviceBehaviour">
<!--<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="WCFSeviceWebHttpBinding.IService1"/>-->
<endpoint address="web" binding="webHttpBinding" bindingConfiguration="basicWebBinding" contract="WCFSeviceWebHttpBinding.IService1"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webhttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"/>
<readerQuotas maxStringContentLength="2147483647"/>
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="basicWebBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"/>
<readerQuotas maxStringContentLength="2147483647"/>
</binding>
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name=""></standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<!--<add name="Access-Control-Allow-Methods" value="*"/>-->
<!--<add name ="Access-Control-Allow-Headers" value="*"/>-->
<!--<add name="Access-Control-Max-Age" value="1728000"/>-->
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
I am stuck to call this service using jquery ajax with json also try jsonp, Here is my aspx page. 我坚持使用带有json的jquery ajax调用此服务,也尝试jsonp,这是我的aspx页面。 I am almost try all web sites and procedure. 我几乎会尝试所有网站和程序。
<script src="Scripts/jquery-1.11.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#tbDetails').hide();
// $('#btnClick').click(function () {
// $.getJSON('http://localhost:34864/Service1.svc/d', function (json) {
// //get information about the user usejquery from twitter api
// $('#txtName').text(json);
// //get the follower_count from the json object and put it in a span
// });
// - See more at: http://usejquery.com/blog/jquery-cross-domain-ajax-guide#sthash.56ebENSb.dpuf
// });
$('#btnClick').click(function () {
alert($("#txtName").val());
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:34864/Service1.svc/d",
//method : 'DoWork',
crossDomain: true,
dataType: "jsonp",
success: function (data) {
alert(data);
},
error: function (result) {
alert(result);
}
});
});
});
</script>
Problem is solved My serive 问题解决了我的服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace WCFSeviceWebHttpBinding
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json )]
[OperationContract]
string DoWork();
}
}
My service implementation 我的服务实施
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
namespace WCFSeviceWebHttpBinding
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string DoWork()
{
return "Hello";
}
}
}
Most importatnt my web.config file 最重要的是我的web.config文件
<?xml version="1.0"?>
<configuration>
<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>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
<wsHttpBinding>
<binding name="NoSecurity">
<security mode="None"/>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WCFSeviceWebHttpBinding.Service1">
<endpoint address="bh" binding="basicHttpBinding" contract="WCFSeviceWebHttpBinding.IService1" />
<endpoint address="wh" binding="wsHttpBinding" contract="WCFSeviceWebHttpBinding.IService1" />
<endpoint address="rh" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="WCFSeviceWebHttpBinding.IService1" behaviorConfiguration="WebBehavior"/>
<endpoint address="jh" binding="wsHttpBinding" bindingConfiguration="NoSecurity" contract="WCFSeviceWebHttpBinding.IService1" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
and now my client is web form hosted in another domain 现在我的客户是另一个域中托管的Web表单
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!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="Scripts/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {
var url = "http://localhost:34864/Service1.svc/rh/DoWork";
$.getJSON(url + "?callback=?", { value: null }, function (data) {
alert(data);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
and my client side web.config 和我的客户端web.config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
<binding name="BasicHttpBinding_IService11" />
</basicHttpBinding>
<wsHttpBinding>
<binding name="WSHttpBinding_IService1" />
<binding name="WSHttpBinding_IService11">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:34864/Service1.svc/bh" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService11" contract="ServiceReference1.IService1"
name="BasicHttpBinding_IService11" />
<!--<endpoint address="http://localhost:34864/Service1.svc/wh" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService1">
<identity>
<userPrincipalName value="SUNIL\IMPOSE" />
</identity>
</endpoint>
<endpoint address="http://localhost:34864/Service1.svc/jh" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService11" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService11" />-->
</client>
</system.serviceModel>
</configuration>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.