【发布时间】:2015-07-10 20:12:54
【问题描述】:
好吧,这里的标题真的很糟糕,但我没有其他方法可以解释我的服务器发生了什么。
我有一个普通的 web api2,新的。我安装了跨域,只放了
config.EnableCors();在webapiconfig。
我有一个包含此方法的 MailController:
[HttpPost]//omUrl/{url?}
[Route(@"~/api/Mail/MailOpen")]
public void MailOpen()
{
try
{
File.Create(@"D:\Emails\Alive.html");
}
catch (Exception ex)
{
// ignored
}
}
并使用此主机在网络上运行:http://localhost:56212/
所以,我正在尝试发布一些数据以检查跨域策略,并使用此 php 代码发布:
<?php
$url = 'http://localhost:56212/api/Mail/MailOpen';
$data = array('Smtp' => 'value1', 'Subject' => 'value2');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
此代码到达服务器并创建 Alive.html,等等。我怎么会问自己,我在这个控制器上还没有任何跨域策略?..
所以我尝试运行这段 javascript 代码:
<script>
$.get(
"http://localhost:56212/api/Mail/MailOpen",
{ 'G': "aa94a7cf-7794-41ff-b8d0-fcfe34fcb19c" }, // put your parameters here
function (responseText) {
console.log(responseText);
}
);
</script>
假设做同样的事情..但我得到这个错误:
jquery-1.11.2.min.js:4 GEThttp://localhost:56212/api/Mail/MailOpen?G=aa94a7cf-7794-41ff-b8d0-fcfe34fcb19cm.ajaxTransport.send@jquery-1.11.2.min.js:4m.extend.ajax@jquery-1.11.2.min.js: 4m.each.m.(匿名函数)@jquery-1.11.2.min.js:4m.extend.getJSON@jquery-1.11.2.min.js:4(匿名函数)@index.html:6 index.html:1 XMLHttpRequest 无法加载 http://localhost:56212/api/Mail/MailOpen?G=aa94a7cf-7794-41ff-b8d0-fcfe34fcb19c。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。响应的 HTTP 状态代码为 405。
这很正常,因为我还没有任何政策。
谁能告诉我为什么 php 工作并且 jQuery 返回错误?
所有。]
编辑:
这更糟糕.. 我刚刚看到我正在尝试使用GET 发布。
所以我将我的请求更改为发布,服务器接受了它并且它工作了,它甚至创建了文件,但是给我一个错误index.html:1 XMLHttpRequest cannot load http://localhost:56212/api/Mail/MailOpen. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
它如何给出错误并且仍然有效?
更好的是,这是怎么回事!?
【问题讨论】:
标签: php security web asp.net-web-api cross-domain