Asp.net

從程式碼隱藏呼叫 ASP.NET Web API

  • January 16, 2017

如何直接從程式碼隱藏呼叫 ASP.NET Web API?或者我應該呼叫從程式碼隱藏中呼叫 getJSON 方法的 javascript 函式嗎?

我通常有類似的東西:

   function createFile() {
       $.getJSON("api/file/createfile",
       function (data) { 
           $("#Result").append('Success!');
       });
   }

任何指針表示讚賞。TIA。

*我正在使用 WebForms。

如果您必須呼叫 Web 服務本身,您可以嘗試HttpClient 按照 Henrik Neilsen 的描述使用。

更新的 HTTPClient 範例

一個基本的例子:

// Create an HttpClient instance 
HttpClient client = new HttpClient(); 

// Send a request asynchronously continue when complete 
client.GetAsync(_address).ContinueWith( 
   (requestTask) => 
   { 
       // Get HTTP response from completed task. 
       HttpResponseMessage response = requestTask.Result; 

      // Check that response was successful or throw exception 
       response.EnsureSuccessStatusCode(); 

       // Read response asynchronously as JsonValue
       response.Content.ReadAsAsync<JsonArray>().ContinueWith( 
                   (readTask) => 
                   { 
                       var result = readTask.Result
                       //Do something with the result                   
                   }); 
   }); 

引用自:https://stackoverflow.com/questions/10307286