我一直在关注Microsoft教程,以设置启用AJAX的WCF服务并与客户端访问它们。但是,尽管准确地遵循了教程,但结果将无法按照应该显示。
我遵循下一个教程的每一步。如果您想追溯我的工作,这可能会很有用。我在Visual Studio 2019中工作,在下面,我粘贴了WCF服务和Web表单的代码。
//WCF service file defining the operation
namespace SandwichServices
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
[OperationContract]
public double CostOfSandwiches(int quantity)
{
return 1.25 * quantity;
}
}
}
//.aspx file for the web form
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SandwichServices.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Calculate() {
CostService.CostOfSandwiches(3, onSuccess);
}
function onSuccess(result) {
var myres = $get("additionResult");
myres.innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/CostService.svc" />
</Services>
</asp:ScriptManager>
<input type="button" value="Price of 3 sandwiches" onclick="Calculate()" />
<br />
<span id="additionResult">
<br />
</span>
</form>
</body>
</html>
调试时,页面将正确生成按钮,但是单击按钮应显示3.75的结果。相反,没有显示结果。查看页面源并检查控制台时会在单击按钮时揭示以下错误:" script5009:'costervice'尚未定义"。在解决此问题方面的任何帮助将不胜感激。
请确保在添加posservice.svc项目时,在配置文件(web.config(中有一个适当的 system.ServiceModel e节。
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication1.CostServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication1.CostService">
<endpoint address="" behaviorConfiguration="WebApplication1.CostServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication1.CostService" />
</service>
</services>
</system.serviceModel>
请使用实用的装配/名称空间替换上述属性。在我这边,我创建了一个 webapplicaiton1 项目,默认名称空间为 webapplicaiton1 。此外, costervice.svc 和 webform3.aspx 都在项目的根目录中。
随时让我知道是否有我可以帮助的。
更新。
最近,我发现这个问题是一个错误。它可以提高IIS中无扩展的URL处理程序,从而导致Web服务无法识别。
https://support.microsoft.com/zh-cn/help/2520479/web-services-may-fail-fail-on-microsoft-internet-internet-information-information-services-iis-7
另外,这是一个解决方法。我们将相对服务地址替换为完整的服务地址(基于托管环境(。
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:56697/Content/CostService.svc" />
</Services>
</asp:ScriptManager>