- What is a Web API
- Routing from an HTTP request to a controller class and method
- What are actions and resources
Step 1 – Create the project
Create a new ASP.NET MVC 4 Web Application and select the Web API template.
Step 2 – Create some models
Models are classes that represent resources on the server. For example, if your Web API has an /api/products collection of resources you should have a model class called Product, like this:
namespace MyWebApp.Models
{
[DataContract]
public class Product
{
[DataMember]
public int ProductId { get; set; }
[DataMember]
public string Name { get; set; }
}
}
Models will be returned by some of the methods on the controllers and finally serialized into XML or JSON before being sent back to the client.
Note the use of the [DataContract] and [DataMember] attributes in this class. They are used to indicate the class and properties/fields that should be serialized. If I were to remove the [DataMember] attribute above the Name property the serialized version of this class will not contain a Name field.
These attributes are not required for simple classes that have no constructors or additional fields that cannot be serialized. However, if I remove all the attributes in the example above the serializer will try to serialize the constructor as well and throw a nasty exception. So as a matter of consistency I recommend adding them even when not required.
Models go in a folder called “Models”:
Step 3 – Create some controllers
A controller is a class that will handle actions that are being performed on server resources. For example, if your Web API has an /api/products collection of resources you should have a controller class called ProductsController, like this:
namespace MyWebApp.Controllers
{
public class ProductsController : ApiController
{
public IEnumerable GetAllProducts()
{
MyWebAppDao dao = new MyWebAppDao();
return dao.FindAllProducts();
}
}
}
For routing to work correctly pay special attention to the names of the class, methods and parameters.
You can add a controller class manually or right-click on the Controllers folder and select Add->Controller to bring up the following menu:
Controllers go in a folder called Controllers:
Step 4 – Test the Web API in your browser:
Compile the project. You should now be able to hit the following URL: http://MyWebServer/MyWebApp/api/products and get an XML list of products back.
No comments:
Post a Comment