跨域调用 WcfRest

 公司项目需要有一个WcfRest服务接口,于是编写了一个 部署后发现,在跨域调用时会出现“not allowed by Access-Control-Allow-Origin”的错误提示,在gg和度娘的帮助下完美解决该问题

Wcf Global:

  
  
  
  
  1. public class Global : HttpApplication 
  2.     { 
  3.         void Application_Start(object sender, EventArgs e) 
  4.         { 
  5.             RegisterRoutes(); 
  6.         } 
  7.         protected void Application_BeginRequest(object sender, EventArgs e) 
  8.         { 
  9.  
  10.             HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
  11.             HttpContext.Current.Response.Cache.SetNoStore(); 
  12.  
  13.             EnableCrossDmainAjaxCall(); 
  14.         } 
  15.         private void EnableCrossDmainAjaxCall() 
  16.         { 
  17.             HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin""*"); 
  18.  
  19.             if (HttpContext.Current.Request.HttpMethod == "OPTIONS"
  20.             { 
  21.                 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods"
  22.                             "GET, POST"); 
  23.                 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers"
  24.                             "Content-Type, Accept"); 
  25.                 HttpContext.Current.Response.AddHeader("Access-Control-Max-Age"
  26.                             "1728000"); 
  27.                 HttpContext.Current.Response.End(); 
  28.             } 
  29.         } 
  30.  
  31.         private void RegisterRoutes() 
  32.         { 
  33.             // Edit the base address of Service1 by replacing the "Service1" string below 
  34.             RouteTable.Routes.Add(new ServiceRoute(""new WebServiceHostFactory(), typeof(Service))); 
  35.         } 

Html:

  
  
  
  
  1. <script type="text/javascript"
  2.         function add(resId, resName, resUrl, goodsId,mid) { 
  3.             var strjson = 
  4.                 { 
  5.                     resId: resId, 
  6.                     resName: resName, 
  7.                     resUrl: resUrl, 
  8.                     goodsId: goodsId, 
  9.                     mid:mid 
  10.                 }; 
  11.             var encode_Entity = $.toJSON(strjson); 
  12.             $.ajax({             url: "http://XXXXXX.XXXXXX.com/WcfRestService/Wardrobe/AddWardrobeRes/"
  13.                 type: "POST"
  14.                 dataType: "json"
  15.                 data: encode_Entity, 
  16.                 contentType: "application/json; charset=utf-8"
  17.                 success: function (data) { 
  18.                     alert(data); 
  19.                 }, 
  20.                 error: function (x, e) { 
  21.                 } 
  22.             }); 
  23.         } 
  24.     </script> 

 

你可能感兴趣的:(跨域,WCF)