2011-02-02 73 views
1

我一直在尋找一個關於如何使用Visual Studio 2010編寫Web服務的很好的指南,這樣我就可以在使用AJAX的基於HTML的網站中使用它。來自JS調用的ASP.NET Web服務

我知道有一種叫做ASMX的方式,但現在它更多地更新到ServiceHost,所以我需要的是一個簡單的指南,可以推動我如何使用ServiceHost對象創建asp.net web服務。

對不起,如果它聽起來含糊或幼稚。

+0

[使用JQuery來調用WebMethod]可能的重複(http://stackoverflow.com/questions/563133/using-jquery-to-call-a-webmethod) – 2011-02-02 07:00:19

回答

2

放置ScriptManager控制你的頁面上添加一個引用您的.asmx服務:

<asp:ScriptManager ID="myManager" runat="server"> 
    <Services> 
     <asp:ServiceReference Path="~/MyService.asmx" /> 
    </Services> 
</asp:ScriptManager> 

在您的web服務的代碼隱藏聲明你的Web方法(注意ScriptService屬性):

namespace MyServices 
{ 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    [ScriptService] 
    public class MyService : System.Web.Services.WebService 
    { 
     [WebMethod] 
     public string SayHello(name) 
     { 
      return "Hello, " + name; 
     } 
    } 
} 

現在你可以消耗從JavaScript web服務類似如下:

function queryWebService() { 
    MyServices.MyService.SayHello('Bobby', 
    function(result, userContext) { 
     alert('Web-service response: ' + result); 
    }, function(result) { 
     alert('Error!'); 
    }); 
} 

UPDATE

如果你想通過簡單地發送一個HTTP GET請求使用的Web服務,那麼你可以做到以下幾點:

裝點您的網絡方法與ScriptMethod屬性:

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public string SayHello(name) 
{ 
    return "Hello, " + name; 
} 

注意UseHttpGet屬性設置爲True。你可能還需要修改web.config文件,以允許這種交互:

<webServices> 
    <protocols> 
     <add name="HttpGet"/> 
    </protocols> 
</webServices> 

現在你可以做一個簡單的HTTP GET請求到Web服務如下圖所示(示例使用jQuery.ajax):

$.ajax({ 
    url: "/MyService.asmx/SayHello?name=Bobby", 
    success: function(transport) { 
     alert('Web-service response: ' + transport.responseText); 
    } 
}); 

希望這會對你有所幫助。

+0

雖然你的嚮導是有幫助的,但我不看爲此解決方案。該服務託管在雲端,Javascript將從不同的客戶端調用它們,所以我需要通過HTTP GET方法調用它們。我可以這樣做嗎? – Neutralizer 2011-02-02 13:57:31