Call ASP.NET Web API from code-behind

让人想犯罪 __ 提交于 2019-12-03 03:03:49
Eric King

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

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

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';
          }

     }

    ...
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!