HI WELCOME TO SIRIS

Calling Cross Domain WCF Service using Jquery

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: OPTION
  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. List GetSuppliers (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.
  2. For running the code, make a virtual directory/web application on IIS and map the code folder to it.
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.