9

如何直接从代码隐藏调用 ASP.NET Web API?或者我应该调用从代码隐藏中调用 getJSON 方法的 javascript 函数吗?

我通常有类似的东西:

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

任何指针表示赞赏。TIA。

*我正在使用 WebForms。

4

3 回答 3

13

如果您必须调用 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                   
                    }); 
    }); 
于 2012-04-25T00:10:24.113 回答
6

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

于 2012-04-24T23:16:38.077 回答
3

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

     }

    ...
 }
于 2012-04-24T23:16:31.530 回答