Tuesday, February 21, 2012

Simplest Web Api Site with Nuget

Here are the steps to create the simplest ASP.Net Web Api with Nuget. If you want to know more about Web Api, go here and read up.

1. Create an Empty Web Application and call it SimpleWebApi.









2. Open your Package Manager Console if it is not already open. Go to View-> Other Windows-> Package Manager Console.

3. Type these two lines
Install-Package AspNetWebApi
Install-Package System.Json

You will see something similar to this:
PM> Install-Package AspNetWebApi
Attempting to resolve dependency 'AspNetWebApi.Core (≥ 4.0.20126.16343)'.
Attempting to resolve dependency 'System.Net.Http.Formatting (≥ 4.0.20126.16343)'.
Attempting to resolve dependency 'System.Net.Http (≥ 2.0.20126.16343)'.
Attempting to resolve dependency 'System.Web.Http.Common (≥ 4.0.20126.16343)'.
'AspNetWebApi 4.0.20126.16343' already installed.
Successfully added 'System.Net.Http 2.0.20126.16343' to SimpleWebApi.
Successfully added 'System.Net.Http.Formatting 4.0.20126.16343' to SimpleWebApi.
Successfully added 'System.Web.Http.Common 4.0.20126.16343' to SimpleWebApi.
Successfully added 'AspNetWebApi.Core 4.0.20126.16343' to SimpleWebApi.
Successfully added 'AspNetWebApi 4.0.20126.16343' to SimpleWebApi.
PM> Install-Package System.Json
'System.Json 4.0.20126.16343' already installed.
Successfully added 'System.Json 4.0.20126.16343' to SimpleWebApi.

4. Right click on the SimpleWebApi project and select Add -> New Item
5. Select Global Application Class and click Add.
6. Open Global.asax and add this line to Application_Start

        protected void Application_Start(object sender, EventArgs e)
        {
            System.Web.Routing.RouteTable.Routes.MapHttpRoute("Default Api", "{Controller}");
        }

7. Add System.Web.Http; to the top of the file.
8. Right click on the SimpleWebApi project and select Add -> New Folder and create a folder name Api. Your project layout should look like this now.








9. Right click on the Api folder and select Add -> Class.
10. Name the class as GreetingController.cs
11. Modify your GreetingController to look like this:

using System;
using System.Web.Http;

namespace SimpleWebApi.Api
{
    public class GreetingController : ApiController
    {
        public string GetGreeting(string name)
        {
            return String.Format("Hello {0}", name);
        }
    }
}
12. Press Ctrl + F5 to run your project. A browser should popup with a Directory listing.
13. Add /Greeting to the end of the url. For example: mine url was http://localhost:4831 so I change it to be http://localhost:4831/Greeting. Your browser should display something similar to this:














14. Now edit your url to be http://localhost:4831/Greeting?World. Remember to make sure your port number is correct. Here is what should be displayed.














You are done. Congratulation!

No comments: