我已尝试在我的webapi应用程序中启用cors,但我不断收到以下消息。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://apitesting.domain1.com/api/stw?{}. This can be fixed by moving the resource to the same domain or enabling CORS.
api / stw {},当我从客户端(通过本地主机)调用它时返回200响应,但是我无法在我的浏览器调试工具的控制台窗口中看到任何数据。
我在webapi的以下文件中启用了cors:
webconfig文件
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
webAPI配置类
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
STW API控制器:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class STWController : ApiController
{
private ### db = new ####();
[HttpGet]
public IEnumerable<Loan> getData()
{
// get data
}
}
我在客户端使用ajax方法从以下位置调用我的服务器数据:
$(document).ready(function () {
$.support.cors = true;
$.ajax({
type: "GET",
crossDomain: true,
// contentType: "application/json; charset=utf-8",
url: "http://apitesting.domain1.com/api/stw",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.toSource());
console.log(data);
for (var i = 0; i < data.length; i++) {
$("#tbDetails").append("<tr><td>" + data[i].Name + "</td><td>" + data[i].loan + "</td><td>" + data[i].evnt + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
在我的浏览器工具的网络标签中,我收到以下请求和响应标题:
回复标题:
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *, *
Cache-Control: no-cache
Content-Length: 321
Content-Type: application/json; charset=utf-8
Date: Tue, 14 Apr 2015 11:04:00 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
请求标题:
Host: apitesting.domain1.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:5472/cors.aspx
Origin: http://localhost:5472
Connection: keep-alive
Web api代码中是否存在我遗漏的内容,这会导致响应和请求标头发生冲突。请指教。感谢。