如何向WCF服务添加跨域支持

我正在尝试允许来自我在localhost:80托管的javascript应用程序的POST请求到托管在不同端口的WCF REStful服务,但不知何故它不起作用。 我已经尝试在标题中添加自定义属性,并在我的服务的JSONData方法中以编程方式添加它,但我仍然在我的响应中得到’405 Method not allowed’。 这里适当的方法是什么?

这是我的界面:

 namespace RestService { public class RestServiceImpl : IRestServiceImpl { #region IRestServiceImpl Members public string JSONData() { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); return "Your POST request"; } #endregion } } 

和服务代码:

 using System.ServiceModel; using System.ServiceModel.Web; using System.Web.Script.Services; namespace RestService { [ServiceContract] public interface IRestServiceImpl { [OperationContract] [ScriptMethod] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "export")] string JSONData(); } } 

最后配置:

                                     

这对我来说比Web.config版本更好:

创建Global.asax

将此方法添加到Global.asax.cs

 using System.Web; namespace StackOverflow { public class Global : System.Web.HttpApplication { protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); } } } } 

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

将这些节点添加到Web.config:

             

参考: http : //theagilecoder.wordpress.com/2014/07/07/wcf-and-cors-no-access-control-allow-origin-header-is-present-on-the-requested-resource/

为非GET请求启用CORS需要的不仅仅是设置Access-Control-Allow-Origin标头 – 它还需要处理预检请求,这是OPTIONS请求,要求服务器执行可能会更改数据的操作是否安全(例如,POST,PUT,DELETE)在发送实际请求之前。

我写了一篇关于为WCF添加CORS支持的博客文章。 这不是最简单的实现,但希望post中的代码可以简单地复制/粘贴到您的项目中。 该post可以在http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx找到。

以下.NET代码(global.asax)有一个重要区别,即代替*,最好回显Origin域,因为这样可以通过CORS(例如NTLM / Kerberos)以及Preflight进行身份validation。

 void Application_BeginRequest(object sender, EventArgs e) { if (Request.HttpMethod == "OPTIONS") { Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); Response.AddHeader("Access-Control-Max-Age", "1728000"); Response.End(); } else { Response.AddHeader("Access-Control-Allow-Credentials", "true"); if (Request.Headers["Origin"] != null) Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]); else Response.AddHeader("Access-Control-Allow-Origin" , "*"); } }