Search code examples
asp.netasmxasp.net-4.5

Difference between page methods and Web API in ASP.NET


I am working on an e-commerce website (ASP.NET 4.5, Web Forms). For showing the review of each product I am using Web API to get data from the server. I am making a GET Ajax call here and the same functionality can be achieved by using page methods in ASP.NET as well.

I am a little confused about the possible advantages of using Web API here over page methods. I have gone through various articles to get to know about Web API but I couldn't find any comparison between Web API and page methods yet.

What are the differences/advantages of Web API over page methods?


Solution

  • At the most basic level the difference is you'll want to avoid using a traditional ASP.NET Web Forms page from serving API requests because it will inherit a large number of methods and events that won't pertain to it at all. For instance, you'll have a Page.MasterPage property exposed on the API class that in no way maps to what an API endpoint would expose.

    To be more direct, you'll be making your API endpoints harder to maintain and to test as well. If you implement them using ASP.NET Web Forms via pages you'll have a new "page" for each API endpoint. This will make it a lot harder to maintain as you'll have buried in tangled code files details for sifting between HTTP POST vs HTTP GET and fighting ASP.NET Web Forms handling of those methods.

    In testing, you'll have to spin up the entire ASP.NET page lifecycle just to get basic parts of the API. So you'll need to spin up full HTTP Context mocks and populate those with a lot of data that doesn't pertain to your API just to get the test runnable. In short, a mess and wasted time since you can avoid all of this going with Web API.

    Web Forms and Web API are just tools. When choosing between the two pick the tool that is best suited for the job. Web Forms is best suited at serving web pages that are CRUD heavy enterprise style pages. Web API is tailored to leverage the advantages of MVC to build RESTful API Endpoints (it can do more than just REST).

    You could get a lot closer to what Web API would offer you in ASP.NET Web Forms by writing a lot of HTTP Handlers, but then you would be reinventing the wheel for no real reason.