【发布时间】:2014-11-22 22:37:17
【问题描述】:
在我的客户端我有这个代码:
<script>
function SignIn() {
$.ajax({
type: 'GET',
url: 'http://localhost:54976/api/values?email=dieter&password=borgers',
contentType: 'text/plain',
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
//data: parameters,
crossDomain: true,
xhrFields: {
withCredentials: false
},
headers: {
'Access-Control-Allow-Origin': '*'
},
success: function (data) {
alert(data);
},
error: function () {
alert("fail");
}
});
}
</script>
然后在我的“本地服务器”端我有这个:
public string Get(string Email, string Password)
{
Request.Headers.Add("Access-Control-Allow-Origin", "*");
return Email + " : " + Password;
}
这在我的 web.config 中:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
我做错了什么? 我总是遇到这个错误:不允许从外部源读取。这可以通过启用 CORS 来帮助解决。
【问题讨论】:
-
我觉得你还需要dataType: "jsonp"
-
您是否尝试过在控制器上使用 Cors 属性?
[EnableCors("*", "*", "*")]? -
两者仍然给我一个失败。
-
您使用的是哪个版本的 Web Api?
-
ID:Microsoft.AspNet.WebApi
标签: javascript c# asp.net-mvc cors