我编写了一个返回 JSON 响应的 WCF 服务。然后我用一些 JavaScript 代码创建了一个 html 页面来测试该功能。当我将服务发布到暂存环境(使用 SSL 模拟生产环境)时,我必须更新服务的 web.config 文件以通过 HTTPS 工作。当我直接浏览到 .svc 端点(服务页面以 http 和 https 显示)以及在浏览器中调用该服务(系统提示我下载 JSON 响应)时,一切似乎都正常,但是当我将测试页面更改为指向 https 版本,我收到“拒绝访问”错误。
这是我的配置文件的服务模型部分的代码:
<system.serviceModel>
<services>
<service name="Services.PromotionCodeGeneration" behaviorConfiguration="md">
<endpoint address="" binding="webHttpBinding" contract="Services.IPromotionCodeGeneration" behaviorConfiguration="webHttp" bindingConfiguration="webBindingSecure"/>
<endpoint address="" binding="webHttpBinding" contract="Services.IPromotionCodeGeneration" behaviorConfiguration="webHttp" bindingConfiguration="webBinding"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="md">
<serviceMetadata httpsGetEnabled="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webBindingSecure">
<security mode="Transport"/>
</binding>
<binding name="webBinding">
<security mode="None"></security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
这是我测试页面的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script>
function api_test() {
var url = "https://test.mydomain.com/Services/PromotionCodeGeneration.svc/contest/useremail@mydomain.com";
var client = new XMLHttpRequest();
client.open("GET", url, false);
client.setRequestHeader("Authentication-Key", "LK589-JIJO-SHG9-0987-65TG-HJKU-Y$GH");
client.send();
var responseText = client.responseText;
var result = JSON.parse(responseText);
document.writeln("Id: " + result.Id + "<br/>");
document.writeln("Code: " + result.Code + "<br/>");
var expiryDate = "";
if (result.Expires != null){expiryDate = result.Expires;}
document.writeln("Expires: " + expiryDate + "<br/>");
document.writeln("Status: " + result.Status + "<br/>");
}
</script>
</head>
<body onload="api_test();">
</body>
</html>
我已经研究这个问题 2 天了。我发现很多人说您不能跨域使用“XMLHttpRequest”方法,但它可以通过基本 http 为我找到它,所以我觉得很难相信。我还尝试了许多不同的服务模型配置建议,但没有一个适用于 https 通信。有没有人在我的配置或调用页面中看到导致通过 https 的“拒绝访问”响应的任何内容?
如有任何帮助,我们将不胜感激。
最佳答案
HTML 页面和服务是否符合 Same Origin Policy ?
域名 必须相同,包括子域(例如,您不能在 test2.example 的页面中加载 test1.example.com 上托管的文件.com)。
协议(protocol)(例如
http
或https
)必须相同。端口 必须相同(例如,您不能从 example.com 的页面加载 example.com:8080 的文件)。
所有 AJAX 请求都需要满足此策略 - 否则,正如@Mike Miller 建议的那样,您可能需要查看 JSONP .
关于javascript - 通过 HTTPS 从 Javascript 调用 WCF 服务导致访问被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6300140/