无法将Access-Control-Allow-Origin添加到我的WCF库Project

我试图理解为什么这个ajax被调用不起作用

$.ajax({ type: 'GET', url: "http://localhost:8732/Design_Time_Addresses/InMotionGIT_NT.Address.Service/AddressService/json/capitalize", data: { streetAddress : JSON.stringify(streetAddress) , consumer : JSON.stringify(consumer)} , datatype: "jsonp", success: function (data) { $('body').append('
'+data.IDblah+' '+ data.prueba+'
'); alert(data.IDblah); }

服务接收数据正确接收并且响应正确。 我为什么做错了?

我尝试将此属性添加到调用的ajax但没有成功crossDomain : true

 [OperationContract()] [WebInvoke(Method="GET", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] public string Capitalize(StreetAddress streetAddress,ConsumerInformation consumer) 

我得到它的错误是常见的

  XMLHttpRequest cannot load Origin http://localhost:50816 is not allowed by Access-Control-Allow-Origin. 

UPDATE

我尝试通过在App.config文件中添加configuracion将响应添加到响应,但没有成功

        

这个链接有用: http : //enable-cors.org/

您需要在响应中添加以下标头,并将其发送回客户端:

//允许所有域名

Access-Control-Allow-Origin: *

要么

//允许特定域名

Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com

将其放在配置文件的服务端

        

这个对我有用! 谢谢!

在Visual Studio,Chrome和Firefox中直接使用我的WCF服务时,我遇到了同样的问题。 我修改了以下内容:

使用以下函数编辑Global.asax文件:

 private void EnableCrossDomainAjaxCall() { 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, Authorization, Accept"); HttpContext.Current.Response.End(); } } 

然后从中调用函数

 protected void Application_BeginRequest(object sender, EventArgs e) { EnableCrossDomainAjaxCall(); } 

您可以从以下url获取更多信息:

http://blog.blums.eu/2013/09/05/restfull-wcf-service-with-cors-and-jquery-and-basic-access-authentication

解决方案是创建一个文件Global.asax

  protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); } } 

可以在此处找到另一种处理此问题的方法,这种方式更适合自托管服务。

对于WCF服务,您必须开发新行为并将其包含在端点配置中:

  1. 创建消息检查器

      public class CustomHeaderMessageInspector : IDispatchMessageInspector { Dictionary requiredHeaders; public CustomHeaderMessageInspector (Dictionary headers) { requiredHeaders = headers ?? new Dictionary(); } public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext) { return null; } public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty; foreach (var item in requiredHeaders) { httpHeader.Headers.Add(item.Key, item.Value); } } } 
  2. 创建端点行为并使用Message Inspector添加标头

      public class EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) { var requiredHeaders = new Dictionary(); requiredHeaders.Add("Access-Control-Allow-Origin", "*"); requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS"); requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type"); endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders)); } public void Validate(ServiceEndpoint endpoint) { } public override Type BehaviorType { get { return typeof(EnableCrossOriginResourceSharingBehavior); } } protected override object CreateBehavior() { return new EnableCrossOriginResourceSharingBehavior(); } } 
  3. 在web.config中注册新行为

          
  4. 向端点行为配置添加新行为

           
  5. 配置端点