我创建了一个WCF服务,它应该由客户端的Javascript(Json)使用。网站由ASP.NET MVC生成。我把所有东西都运行在localhost IIS-Express上。 问题是,当我从Javascript调用此WCF服务时,它会抛出并且未定义错误。 许多想法之一,为什么会出现此错误,WCF web.config设置不正确,并且不允许跨站点脚本。
这是web.config文件
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service behaviorConfiguration="Default"
name="Wcf_Categories.Categories">
<endpoint address=""
behaviorConfiguration="webBehavior"
binding="webHttpBinding"
contract="Wcf_Categories.ICategories" />
<endpoint address="sc"
behaviorConfiguration="script"
binding="webHttpBinding"
bindingConfiguration="crossDomain"
contract="Wcf_Categories.ICategories"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding"
address="mex" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true" />
</behavior>
<behavior name="script">
<enableWebScript/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
如果我直接从浏览器调用服务,例如localhost:1813 / Categories.svc / sc / GetData?name = undefined 它返回建议的数据并且行为正常(在localhost / TestSites / Products#上运行的站点)
这是wcf服务调用的脚本
function GetCategories(categoryName) {
$.ajax({
type: "GET",
async: "false",
url: "localhost:1813/Categories.svc/sc/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data : 'name='+categoryName,
processData: true,
success: function (result) {
ServiceSucceeded(result);
},
error: ServiceFailed
});
}
function ServiceSucceeded(result) {
var resultObject;
if (DataType == "json") {
resultObject = result.GetUserResult;
for (i = 0; i < resultObject.length; i++) {
alert(resultObject[i]);
}
}
}
function ServiceFailed(xhr) {
alert(xhr.responseText);<---------------------- Alert output is "undefined". Exception details = [Exception... "<no message>" nsresult: "0x805e0006 (<unknown>)" location: "JS frame :: http://localhost/TestSites/content/js/jquery-1.10.2.min.js :: .send :: line 6" data: no] ------->
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." });
}
return;
}