2017-04-19 33 views
1

內部webservices使用soap通過HTTP進行工作。但是,當我們嘗試訪問Web服務的[WebMethod]時,如何根據jQuery Ajax的URL開始工作? SOAP仍然在使用jQuery ajax發揮作用嗎?如果是的話如何?如果不是爲什麼不呢?你可以使用下面的例子來保持簡單。asp.net webservices(.asmx)

下面是ASMX代碼:

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
public class MyService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    public string HelloWorld() 
    {   
     return "Hello World"; 
    } 
} 
+0

也SOAP頭如何使用jQuery AJAX工作 – Var

+0

@AndriiLitvinov請不要用'內聯代碼「來突出顯示隨機條款。 – CodeCaster

+0

@CodeCaster,你能詳細說一下嗎?或者,也許提供鏈接到維基?我認爲在科技事物突出時更容易閱讀。 –

回答

0

它可以調用WebMethodsAJAX作爲傳輸是HTTP。你可以找到它的許多例子在互聯網和SO:

jQuery AJAX call to an ASP.NET WebMethod

Calling ASP.Net WebMethod using jQuery AJAX

SOAP是有效載荷的信封(有一些額外的功能)。是否要在WebMethod中使用它取決於您。

這裏是你如何在Web應用程序項目創建一個Hello World服務:

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class WebService1 : System.Web.Services.WebService 
{ 
    [WebMethod] 
    public string HelloWorld() 
    { 
     return "Hello World"; 
    } 
} 

這裏是你如何用jQuery使用它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 

<script> 
    console.log($.ajax); 
    $.ajax({ 
     type: "POST", 
     url: "http://localhost:55501/WebService1.asmx/HelloWorld", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function(response.d) { 
      alert(response.d); 
     } 
    }); 
</script> 

而且從服務器的響應將是{d: "Hello World"}因爲jQuery將添加Accept頭文件「application/json」。

這裏是如何從控制檯應用程序使用它:

static void Main(string[] args) 
{ 
    var client = new HttpClient(); 
    var uri = new Uri("http://localhost:55501/WebService1.asmx/HelloWorld") 

    // Get xml 
    var response = client.PostAsync(uri, new StringContent("")).Result; 
    Console.WriteLine(response.Content.ReadAsStringAsync().Result); 

    Console.WriteLine(); 

    // Get Json 
    var response1 = client.PostAsync(uri, 
     new StringContent("", Encoding.UTF8, "application/json")).Result; 
    Console.WriteLine(response1.Content.ReadAsStringAsync().Result); 
} 

這將輸出:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">Hello World</string> 

{"d":"Hello World"} 
+0

嗨Andrii謝謝你的回答,請你舉個例子來解釋一下。我知道如何用jquery ajax調用webmethod。我想知道當w在應用程序中使用asmx服務(在Web應用程序或控制檯應用程序中)時,內部如何工作(soap消息的searlization),以及當我們從ajax調用webmethod時事物如何自動變化。 – Var

+0

Nothings自動更改。 SOAP是通過HTTP的通信協議。因此,如果客戶端是另一個應用程序或瀏覽器,則無關緊要。 –

+0

@ user7889160,我用例子更新了我的答案。 –