Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call ASP.NET Web API from code-behind

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.

like image 274
Rivka Avatar asked Apr 24 '12 23:04

Rivka


People also ask

What is code behind in ASP?

Code-behind refers to code for your ASP.NET page that is contained within a separate class file. This allows a clean separation of your HTML from your presentation logic.

Can I use Web API with ASP.NET webform?

Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. To use Web API in a Web Forms application, there are two main steps: Add a Web API controller that derives from the ApiController class. Add a route table to the Application_Start method.


3 Answers

You should refactor the logic into a separate backend class and call it directly from youir code-behind and from the Web API action.

like image 155
SLaks Avatar answered Sep 28 '22 06:09

SLaks


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                   
                    }); 
    }); 
like image 30
Eric King Avatar answered Sep 28 '22 06:09

Eric King


Recommended in many software architecture books is that you shouldn't put any business logic in your (API)controller code. Assuming you implement it the right way, for instance that your Controller code currently accesses the business logic through a Service class or facade, my suggestion is that you reuse the same Service class/facade for that purpose, instead of going through the 'front door' (so by doing the JSON call from code behind)

For basic and naieve example:

public class MyController1: ApiController {

    public string CreateFile() {
        var appService = new AppService();
        var result = appService.CreateFile(); 
        return result;
    }

}

public class MyController2: ApiController {

   public string CreateFile() {
       var appService = new AppService();
       var result = appService.CreateFile(); 
       return result;
   }
}

AppService class encapsulates your business logic (and does live on another layer) and makes it easier for you to access your logic:

 public class AppService: IAppService {

     public string  MyBusinessLogic1Method() {
       ....
       return result;
     }
     public string  CreateFile() {

          using (var writer = new StreamWriter..blah die blah {
            .....
            return 'whatever result';
          }

     }

    ...
 }
like image 41
S P Avatar answered Sep 28 '22 06:09

S P