【转】Calling Cross Domain WCF Service using Jquery

本文介绍如何解决跨域调用WCF服务的问题。通过配置web.config文件及使用jQuery发起请求,实现不同域间WCF服务的成功调用。文中还提供了一个具体的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

From last couple of days, I was trying to call a wcf service using jquery that is hosted in different domain. But every time I was failed to call wcf service from different domain. After spending much time on R&D, I found the solution and the reason why I was unable to call cross domain wcf service.

Whenever you try to call a cross domain WCF Service by javascript or jquery, it behaves differently with different browsers. When you want to perform "POST" or "GET" request on cross domain wcf service or normal service using jquery/javascript or ajax, the browser actually sends an "OPTIONS" verb call to your wcf service that is not mention in your wcf method attribute. We mention there "POST" or "GET" to call a wcf service method. Hence we get error to call cross domain wcf service. We find the following request and response headers in firefox when we try to call wcf service.

Request Headers

 
  
  1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1
  2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0
  3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  4. Accept-Language: en-us,en;q=0.5
  5. Accept-Encoding: gzip, deflate
  6. Proxy-Connection: keep-alive
  7. Origin: http://192.168.4.156:90
  8. Access-Control-Request-Method: POST
  9. Access-Control-Request-Headers: content-type
  10. Pragma: no-cache
  11. Cache-Control: no-cache

Response Headers

 
  
  1. HTTP/1.0 405 Method Not Allowed
  2. Cache-Control: private
  3. Allow: POST
  4. Content-Length: 1565
  5. Content-Type: text/html; charset=UTF-8
  6. Server: Microsoft-IIS/7.0
  7. X-AspNet-Version: 4.0.30319
  8. X-Powered-By: ASP.NET
  9. Access-Control-Allow-Origin: *
  10. Access-Control-Allow-Headers: Content-Type
  11. Date: Fri, 04 May 2012 12:05:17 GMT
  12. X-Cache: MISS from c1india.noida.in
  13. X-Cache-Lookup: MISS from c1india.noida.in:3128
  14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21)
  15. Proxy-Connection: close

In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.

Configure WCF Cross Domain service

 
  
  1. namespace CrossDomainWcfService
  2. {
  3. [DataContract]
  4. public class Supplier
  5. {
  6. [DataMember] public string Name;
  7. [DataMember] public string Email;
  8. }
  9. [ServiceContract(Namespace = "")]
  10. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  11. public class MyService
  12. {
  13. [OperationContract]
  14. [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  15. ListGetSuppliers (int OrgID)
  16. {
  17. // Fetch data from database var q= (from tbl in mobjentity.Customer
  18. where tbl.OrgID=OrgID).ToList();
  19. Listlst= new List();
  20. foreach(var supp in q)
  21. {
  22. Supplier msupp=new Supplier();
  23. msupp.Name=supp.Name;
  24. msupp.Email=supp.Email
  25. //Make Supplier List to retun
  26. lst.Add(msupp);
  27. }
  28. return lst;
  29. }
  30. }
  31. }

WCF Service Web.config

 
  
  1. <system.webServer>
  2. <modules runAllManagedModulesForAllRequests="true" />
  3. <httpProtocol>
  4. <customHeaders>
  5. <add name="Access-Control-Allow-Origin" value="*" />
  6. <add name="Access-Control-Allow-Headers" value="Content-Type" />
  7. </customHeaders>
  8. </httpProtocol>
  9. </system.webServer>
  10. <system.serviceModel>
  11. <behaviors>
  12. .
  13. .
  14. .
  15. </behaviors>
  16. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  17. <standardEndpoints>
  18. <webScriptEndpoint>
  19. <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
  20. </webScriptEndpoint>
  21. </standardEndpoints>
  22. <services>
  23. .
  24. .
  25. </service>
  26. </services>
  27. <bindings>
  28. .
  29. .
  30. </bindings>
  31. <client>
  32. .
  33. .
  34. </client>
  35. </system.serviceModel>

Global.asax Code

You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.

 
  
  1. protected void Application_BeginRequest(object sender, EventArgs e)
  2. {
  3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);
  4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
  5. {
  6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser
  7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
  8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
  9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );
  10. HttpContext.Current.Response.End();
  11. }
  12. }

Wcf calling using Jquery

 
  
  1. $.ajax({
  2. type: "Post"
  3. url: "http://www.yourdomain.com/MyService.svc/GetSuppliers", // Location of the service
  4. data: '{"OrgID"="1"}', //Data sent to server
  5. contentType: "application/json;charset-uf8", // content type sent to server
  6. dataType: "json", //Expected data format from server
  7. success: function (msg) {
  8. //Implement get data from service as you wish
  9. },
  10. error: function (err) {
  11. // When Service call fails
  12. }
  13. });
Note
  1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.

Summary

In this article I try to explain cross domain wcf service calling with example. I hope after reading this article you will be able to call cross domain wcf service. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article. You can download demo project from below link.

 

 

 

 

原文:http://www.dotnet-tricks.com/Tutorial/wcf/X8QN260412-Calling-Cross-Domain-WCF-Service-using-Jquery.html 

转载于:https://www.cnblogs.com/taoqianbao/archive/2012/10/19/2730973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值