从代码隐藏中调用ASP.NET Web API

时间:2012-04-24 23:13:15

标签: asp.net webforms getjson asp.net-web-api

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

我通常有类似的东西:

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

任何指针都表示赞赏。 TIA。

*我正在使用WebForms。

3 个答案:

答案 0 :(得分:13)

如果您必须自行调用网络服务,可以尝试使用HttpClient as described by Henrik Neilsen

Updated HTTPClient Samples

一个基本的例子:

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

答案 1 :(得分:6)

您应该将逻辑重构为一个单独的后端类,并直接从您的代码隐藏和Web API操作中调用它。

答案 2 :(得分:3)

许多软件架构书籍中推荐您不应在您的(API)控制器代码中添加任何业务逻辑。假设您以正确的方式实现它,例如您的Controller代码当前通过Service类或Facade访问业务逻辑,我的建议是您为此目的重用相同的Service类/ Facade,而不是通过'前门'(所以通过后面的代码执行JSON调用)

对于基本和naieve的例子:

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类封装了您的业务逻辑(并且可以在另一层上运行),并使您更容易访问逻辑:

 public class AppService: IAppService {

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

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

     }

    ...
 }