7

我试图理解为什么这个调用的 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.

更新

我试图通过在我的文件中添加配置来将标题添加到响应中,App.config但没有成功

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

6 回答 6

14

把它放在配置文件的服务端

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

这个对我有用!谢谢!

于 2013-10-22T12:29:49.913 回答
4

此链接将有所帮助:http ://enable-cors.org/

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

//允许所有域

Access-Control-Allow-Origin: *

或者

//允许特定域

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

于 2012-05-25T20:33:15.560 回答
2

解决方案是创建一个文件 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();
    }
}
于 2015-09-21T22:43:57.810 回答
1

直接在 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();
    }

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

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

于 2014-07-11T08:27:54.450 回答
0

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

于 2016-03-22T14:10:49.870 回答
0

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

  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" />
    
于 2018-01-30T09:32:43.980 回答