我试图理解为什么这个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>
答案 0 :(得分:12)
将其放在配置文件的服务端
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
对我有用!谢谢!
答案 1 :(得分:3)
此链接有助于:http://enable-cors.org/
您需要在回复中将以下标题添加回客户端:
//允许所有域名
Access-Control-Allow-Origin: *
OR
//允许特定域
Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com
答案 2 :(得分: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();
}
}
答案 3 :(得分: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();
}
您可以从以下网址获取更多信息:
答案 4 :(得分:0)
可以找到另一种处理此问题的方法,这种方式更适合自托管服务{。{3}}。
答案 5 :(得分:0)
对于WCF服务,您必须开发新行为并将其包含在端点配置中:
创建邮件检查器
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);
}
}
}
创建端点行为并使用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<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();
}
}
在web.config中注册新行为
<extensions>
<behaviorExtensions>
<add name="crossOriginResourceSharingBehavior" type="Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral" />
</behaviorExtensions>
</extensions>
向端点行为配置添加新行为
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp />
<crossOriginResourceSharingBehavior />
</behavior>
</endpointBehaviors>
配置端点
<endpoint address="api" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="Service.IServiceContract" />