Call ASP.NET Web API from code-behind

Rivka picture Rivka · Apr 25, 2012 · Viewed 27.2k times · Source

How would I call an ASP.NET Web API directly from code-behind? Or should I be calling my javascript function that calls the getJSON method from code-behind?

I usually have something like:

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

Any pointers appreciated. TIA.

*I'm using WebForms.

Answer

Eric King picture Eric King · Apr 25, 2012

If you must call the web service itself, you can try using HttpClient as described by Henrik Neilsen.

Updated HTTPClient Samples

A basic example:

// 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                   
                    }); 
    });