lunedì 5 novembre 2012

Using ASP.NET Web Api on a Web Forms application

One of the most common ways to create a RESTful service using the enviroment of Our Master Bill is to adopt Web Api. Web Api was created to work mainly inside an ASP.NET MVC project...but when we are dealing with a Web Forms project?

Luckly the best scientists from all over the world proved that is it possible with a relatively small effort:

  • Let's start with the basics: if you need to run Web Api on your web application you need to build it AT LEAST on framework 4.0
  • Modify Global.asax as follows (this is made to handle the routing of the url):
    //imports the necessary namespaces
    using System.Web.Routing
    using System.Web.Http
    public class Global : System.Web.HttpApplication
            protected void Application_Start(object sender, EventArgs e)
                //add the routing      
                             new { id = System.Web.Http.RouteParameter.Optional });
  • Create in the App_Code folder a class (or more classes) that inherits from ApiController, this will contain every service that you want to provide on your service:
        public class YourApiController : ApiController
            public string HelloWarLord()
                return "Hello Kitty"; 
            public object GetSomethingById(int id)
                return new NuclearBomb(id);
  • the URL to call in this case is [urlwebapplication]/api/YourApi/ to call HelloWarLord and [urlwebapplication]/api/YourApi/1 to call GetSomethingById. obviously this logic changes depending on the routing indicated previously on Application_Start function, to modify this behaviour you need to jerk with MapHttpRoute function.
folks, that's pretty much it. Enjoy!

Nessun commento:

Posta un commento