关键词:
【中文标题】无法将 Access-Control-Allow-Origin 添加到我的 WCF 库项目【英文标题】:Could not add Access-Control-Allow-Origin to my WCF library Project 【发布时间】:2012-06-01 10:10:16 【问题描述】:我试图理解为什么这个调用的 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>
【问题讨论】:
我也遇到了同样的问题,请问您的问题是怎么解决的?谢谢。 【参考方案1】:把它放在你的配置文件的服务端
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
它对我有用!谢谢!
【讨论】:
在我的 WCF REST 和 SOAP Web 服务上为我工作:)【参考方案2】:此链接会有所帮助:http://enable-cors.org/
您需要在发送回客户端的响应中添加以下标头:
//允许所有域
Access-Control-Allow-Origin: *
或
//允许特定域
Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com
【讨论】:
也应该是数据类型而不是数据类型。同样在上面尝试将响应放入脚本标记中,如果它没有包装在服务器上 好的,所以我将配置添加到我的项目中,但仍然没有将标头发送给客户端我用我的配置更新了我的问题 这里也一样,我添加了相同的几个自定义类,它确实符合该逻辑,但响应仍然没有标题。【参考方案3】:解决办法是创建一个文件 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();
【讨论】:
【参考方案4】:直接在 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.
【讨论】:
【参考方案5】:另一种处理方式,更适合自托管服务,可以找到here。
【讨论】:
【参考方案6】:对于 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);
创建端点行为并使用消息检查器添加标题
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" />
【讨论】:
我也面临同样的问题,我使用了你的代码,现在我面临以下错误“类型'Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral'注册扩展无法加载“crossOriginResourceSharingBehavior””通过 Axios 从 Javascript 代码发布到 .net Web Api 时,Access-Control-Allow Headers CORS 错误
】通过Axios从Javascript代码发布到.netWebApi时,Access-Control-AllowHeadersCORS错误【英文标题】:Access-Control-Allow_HeadersCORSerrorwhenpostingto.netWebApifromJavascriptcodeviaAxios【发布时间】:2021-01-0112:44:46【问题描述】:我正在使用Axios执行从javascrip... 查看详情
Vue + axios:已被 CORS 策略阻止
...'axios\'导入axiosconsttoken=\'xxxxxxxxx\'axios.defaults.headers.common[\'Access-Control-Allow- 查看详情
CORS 不会在 html 或 php 文件中更改
...LHttpRequest无法加载http://error.hostinger.eu/?。不请求中存在“Access-Control-Allow- 查看详情
node---express
varexpress=require(‘express‘);varapp=express();varbodyParser=require("body-parser");app.use(bodyParser.urlencoded({extended:false}));app.all(‘*‘,function(req,res,next){res.header(‘Access-Control-Allow 查看详情
无法将 createdAt 和 updatedAt 保存为日期时间值,也无法将后端保存为前端
】无法将createdAt和updatedAt保存为日期时间值,也无法将后端保存为前端【英文标题】:Can\'tsavecreatedAtandupdatedAtasdatetimevaluesnorbackendneitherfrontend【发布时间】:2020-05-0602:11:48【问题描述】:我正在尝试将日期时间值保存在TodoForm中... 查看详情
“无法将图像数据写入路径” - Laravel 图像干预
】“无法将图像数据写入路径”-Laravel图像干预【英文标题】:"Can\'twriteimagedatatopath"-LaravelImageIntervention【发布时间】:2020-02-0623:18:36【问题描述】:无法将图像数据写入路径(Laravel)我无法将任何内容保存到Laravel项目... 查看详情
无法将 Snapkit 导入 KeyboardViewController
】无法将Snapkit导入KeyboardViewController【英文标题】:CannotimportSnapkitintoKeyboardViewController【发布时间】:2016-06-1808:59:59【问题描述】:我无法将SnapKit导入到KeyboardViewController(UIInputViewController)类,它说没有这样的模块SnapKit。【问题... 查看详情
无法将数据修补到 FormArray
】无法将数据修补到FormArray【英文标题】:UnabletopatchdatatoFormArray【发布时间】:2018-09-1720:17:12【问题描述】:无法将值修补到FormArrayresultList。谁能解释一下,我错过了什么?TS文件:importComponent,OnInitfrom\'@angular/core\';importStudentfr... 查看详情
为啥我无法正确获取图像数据或无法将数据发送到服务器?
】为啥我无法正确获取图像数据或无法将数据发送到服务器?【英文标题】:Whyiamnotgettingimagedataproperlyorunabletosenddatatoserver?为什么我无法正确获取图像数据或无法将数据发送到服务器?【发布时间】:2016-12-2810:26:31【问题描述】... 查看详情
无法将图像提取为 PDF
】无法将图像提取为PDF【英文标题】:CannotextractimageintoPDF【发布时间】:2020-08-0700:16:51【问题描述】:我使用jpgraph库来制作图表,FPDF用于将图表图像复制到PDF中。我可以在网站上查看图表,但无法将图表作为图像复制到PDF中。... 查看详情
无法将 WCF 添加为服务引用
】无法将WCF添加为服务引用【英文标题】:UnabletoaddWCFasservicereference【发布时间】:2020-08-2003:40:13【问题描述】:我无法将此WCF作为服务引用添加到我的项目中。这是发生错误的详细信息。文档已被理解,但无法处理。-WSDL文档... 查看详情
无法将 .json 文件从 CSV 下载到 JSON 转换并且无法将 JSON 转换为 CSV
】无法将.json文件从CSV下载到JSON转换并且无法将JSON转换为CSV【英文标题】:Cannotdownload.jsonfilefromCSVtoJSONConversionandCannotconvertJSONtoCSV【发布时间】:2019-02-0314:51:51【问题描述】:我的将CSV转换为JSON数据的算法有效,但是当我单击... 查看详情
SQLBrowser 将无法启动
】SQLBrowser将无法启动【英文标题】:SQLBrowserwillnotstart【发布时间】:2010-03-1720:59:40【问题描述】:WindowsServer2003x64上的SQLServer2005x64,具有多个实例(默认+2个命名)。工程师将服务器移至不同的域。从那时起,无法让SQLBrowser启... 查看详情
无法将 HttpContext 强制转换为用户
】无法将HttpContext强制转换为用户【英文标题】:UnabletocastHttpContexttoUser【发布时间】:2021-06-0908:36:13【问题描述】:我正在使用WebAPI。我遵循了有关实施JWTAuth的教程。当我使用Postman并获得令牌并尝试进行身份验证时,它可以工... 查看详情
无法将 JSON 响应添加到领域
】无法将JSON响应添加到领域【英文标题】:CannotaddJSONresponsetorealm【发布时间】:2016-05-2502:53:23【问题描述】:我正在尝试将我的POST响应添加到领域,但我抛出了这个错误:无法将“字符串”类型的值转换为预期的参数类型“对... 查看详情
无法将组件添加到扩展 JFrame 的类
】无法将组件添加到扩展JFrame的类【英文标题】:Can\'taddcomponentstoaclassthatextendsJFrame【发布时间】:2012-11-2113:15:31【问题描述】:我正在尝试编写人生游戏。但是,无论我多么努力,我似乎都无法使用按钮将Cell组件添加到框... 查看详情
无法将 ReactiveUI 添加到 NUnit 测试项目
】无法将ReactiveUI添加到NUnit测试项目【英文标题】:Can\'taddReactiveUItoaNUnitTestProject【发布时间】:2015-11-3014:03:03【问题描述】:我目前正在尝试设置Unit以使用NUnit和Moq对我们的ReactiveUIViewModel进行单元测试。但是我无法让它工作。... 查看详情
无法将数据插入现有 BigQuery 表?
】无法将数据插入现有BigQuery表?【英文标题】:UnabletoinsertdataintoexistingBigQueryTable?【发布时间】:2019-08-2613:33:51【问题描述】:我正在尝试将一些数据插入到已经存在的bigquery表中。但我无法将该数据放入表中。我尝试了google(in... 查看详情