[英]How to display result of a WCF service through a client
我一直在關注有關設置啟用AJAX的WCF服務並通過客戶端訪問它們的Microsoft教程。 但是,盡管嚴格按照本教程進行操作,但結果不會按預期顯示。
我遵循了以下教程中的所有步驟。 如果您想追溯我的工作,這可能會很有用。 我在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:未定義'CostService'”。 解決此問題的任何幫助將不勝感激。
將CostService.svc項目添加到項目時,請確保配置文件(web.config)中有適當的System.servicemodel部分。
<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 。 此外, CostService.svc和WebForm3.aspx都位於項目的根目錄中。
請隨時告訴我是否有什么我可以幫助的。
更新。
最近,我發現此問題是一個錯誤。 這是由於IIS中的無擴展名URL處理程序導致Web服務無法識別。
https://support.microsoft.com/zh-cn/help/2520479/web-services-may-fail-on-microsoft-internet-information-services-iis-7
另外,這是一種解決方法。 我們將相對的服務地址替換為完整的服務地址(基於托管環境)。
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:56697/Content/CostService.svc" />
</Services>
</asp:ScriptManager>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.