Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.
While ASP.NET MVC tends to get most of the attention these days, ASP.NET Web Forms and its related controls allow developers to generate powerful, interactive UIs in a short period of time—which is why there are so many ASP.NET Web Forms applications around. What ASP.NET Web Forms doesn’t support is implementing the Model-View-Controller (MVC) and Model-View-ViewModel (MVVM) patterns, which can enable test-driven development (TDD).
The ASP.NET Web API (“Web API” hereafter) provides a way to build or refactor ASP.NET Web Forms applications to the MVC pattern by moving code from the codebehind file to a Web API controller. This process also enables ASP.NET applications to leverage Asynchronous JavaScript and XML (AJAX), which can be used to create a more responsive UI and improve an application’s scalability by moving logic into the client and reducing communication with the server. This is possible because the Web API leverages the HTTP protocol and (through coding by convention) automatically takes care of several low-level tasks. The Web API paradigm for ASP.NET that this article proposes is to let ASP.NET generate the initial set of markup sent to the browser but handle all of the user’s interactions through AJAX calls to a standalone, testable controller.
Setting up the infrastructure to have a Web Forms application interact with the server through a set of AJAX calls isn’t difficult. But I won’t mislead you: Refactoring the code in the Web Forms application code file to work in a Web API controller might not be a trivial task. You have to give up the various events fired by the controls, auto-generated server-side validation and the ViewState. However, as you’ll see, there are some workarounds for living without these features that can reduce the pain.
Adding Web API Infrastructure
To use the Web API in an ASP.NET project, all you need to do (after adding the NuGet Microsoft ASP.NET Web API package) is right-click and select Add | New Item | Web API Controller Class. If you cannot see the Web API Controller Class in the dialog, ensure that you have the NuGet Microsoft ASP.NET Web API package installed, and that you select Web from the items under the desired programming language. However, adding the controller this way creates a class with a lot of default code that you’ll just have to delete later. You might prefer to simply add an ordinary class file and have it inherit from the System.Web.Http.ApiController class. To work with the ASP.NET routing infrastructure, your class name must end with the string “Controller.”