English 中文(简体)
无法将 Access- control- Allow- Oligin 添加到我的 WCF 图书馆项目
原标题:Could not add Access-Control-Allow-Origin to my WCF library 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( <div> +data.IDblah+   + data.prueba+ </div> );
            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 文件中添加配置, 从而添加响应的页眉, 但未成功 。

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</system.webServer>
最佳回答

此链接将有助于: < a href=> "http://enable- cors.org/" rel="no follow" >http://enable- cors.org/

您需要将以下信头添加回寄给客户端的回复中 :

// 所有域名 // 所有域名

Access-Control-Allow-Origin:_/code> (允许控制-Allow-Origin):_/code)

// 指定具体领域

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

问题回答

将此放入您的配置文件的服务侧面

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</system.webServer>

对我管用,谢谢

解决方案是创建文件 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();
    }
}

I was getting the same problem when working with my WCF service directly in Visual Studio, in Chrome and Firefox. I fixed it with the following:

以以下函数编辑 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/restull-wcf-service-with-cors-and-jquery-and-simport-access-audetitution

处理该问题的另一种方式对自办服务来说更好,可找到

对于周转基金服务,您必须发展新的行为,并将其纳入终端配置:

  1. 创建信件检查器

        public class CustomHeaderMessageInspector : IDispatchMessageInspector
        {
            Dictionary<string, string> requiredHeaders;
            public CustomHeaderMessageInspector (Dictionary<string, string> headers)
            {
                requiredHeaders = headers ?? new Dictionary<string, string>();
            }
    
            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. 创建端点行为并使用信件检查员添加信头

        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<string, string>();
    
                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 中注册新行为

    <extensions>
     <behaviorExtensions>        
                <add name="crossOriginResourceSharingBehavior" type="Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral" />        
      </behaviorExtensions>      
    </extensions>
    
  4. 在端点行为配置中添加新行为

    <endpointBehaviors>      
     <behavior name="jsonBehavior">
      <webHttp />
       <crossOriginResourceSharingBehavior />
     </behavior>
    </endpointBehaviors>
    
  5. 配置端点

    <endpoint address="api" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="Service.IServiceContract" />
    




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...