CodeCloudy

Azure | .Net | JQuery | Javascript | Umbraco

Asp.net Web API 102 – Scaffolding

In the previous blog we discussed the Basics of Web API and try to understand the default code. Now we will try to create our custom Web API using a Case Study.

Case study:

We will build our own requirement.

  • We have a Public Product Catalog
  • Any organization or an individual can publish their products here
  • We will add more requirements when we move forward…

Step 1: Create a Model “Product”


(Note: I have put full namespaces so you can better understand where it came from.)

I have added some data annotations to the properties.

  • ID will be the Key property.
  • Name property is marked as required.
  • And the maximum length of the Description will be 500 characters.

Now let’s use Scaffolding to create the Controller using the Model “Product”.

Step 2: Select Scaffolding for Web API 2 with Entity Framework

Right Click Controller Folder à Add à Select “New Scaffolded Item”


Choose the following option in the Web API category:


Step 3: Populate Controller Details for Scaffolding

  • Give a Controller Name
  • You have the option to create Controllers with Asynchronous Controller Actions or without.
  • Select the Model Class “Product”
  • Create a New Data Context to work with Databases.


Error 1:

When scaffolding the controller from the Model following error may appear:

“There was an error generating ‘WebAPI1.Models.DBContext. Try rebuilding your project.”

Rebuilding the project would solve this error.

Error 2:

If the Product class doesn’t have a key property, when scaffolding following error may appear. Example: if ID property doesn’t have the Data Annotation Key.


Note: Make sure you rebuild the project after you add the Key property. Also rebuild after any changes in the Model, before Scaffolding.

Now you have Created the your custom API Controller “ProductController”.

In the next blog we will see the differences of Actions with and without Asynchronous behavior.


Advertisements
Leave a comment »

Asp.net Web API 101 – Basics

We will discuss some points and try to find “Why Web Api?”

  • Earlier we had following web services:

    • Soap services – supports only xml

    • WCF services – supports many data formats, Protocols: HTTP, TCP, UDP, and custom transports

      • For a comparison between SOAP & WCF: Here

      • For a comparison between WCF & Web Api: Here

  • Now apps are available in PCs, Mobiles, Tablets, Notebooks, electronic devices, etc. Not all these devices speak SOAP. But they do speak HTTP. When you have more clients, you need to scale. Web API tries to minimize unnecessary configurations and keeps it simple.
  • It is simply a framework that allows you to build HTTP services. Services that are activated by simple GET requests, or by passing plain XML over POST, and respond with non-SOAP content such as plain XML, a JSON string, or any other content that can be used by the consumer.
  • WCF was initially created to support SOAP + WS-* over a variety of transports. Not all platforms and devices support soap. There was need to non-SOAP services. WCF 3.5 added WebHttpBinding – a new binding to create non-SOAP service over HTTP, better known as a RESTful service. Although, WCF support increased over time, it came with some pain. So, the main goal of the Web APIs is to stop looking at HTTP through the eyes of WCF, and just use as a transport protocol to pass requests. Web API aims to properly use URIs, HTTP headers, and body to create HTTP services accessible by any devices and platforms available.

To Start a Web Api Project using Visual Studio 2013

  • Create a New ASP.NET Web Application


  • Select Web Api template


The project creates a sample Web API controller named “ValuesController”. It will be inherited from the ApiController class which defines properties and methods for API controller.

Since Web API is a http service, each controller will by default have HTTP METHODS.

  • GET
  • POST
  • PUT
  • DELETE

Exercise 1:

http://localhost:16107/api/values

This URL will call the default Method “Get”

    // GET api/values

        public IEnumerable<string> Get()

        {

            return new string[] { “value1”“value2” };

        }

This will return a string array. Example: we can use this to retrieve a product catalog.

Exercise 2:

http://localhost:16107/api/values/001

This URL will call the default Method “Get”, now passing a parameter id.

        // GET api/values/5

        public string Get(int id)

        {

            return “value”;

        }

Example: we can use this to retrieve product by passing a product id.

Exercise 3: POST simple Json string using fiddler

We can use Fiddler, to send a POST requests.




FromBody attribute:

This forces Web API to read a simple type from the request body. However, only one argument in the action can be decorated with this attribute, and you get an exception when you try to decorate more than one. Without FromBody attribute it will return an error “HTTP/1.1 405 Method Not Allowed”. More

Exercise 4: POST Json Object using fiddler

Post Body = { “ProductName”=”Apple”, “Price”=”22”}


Exercise 5: POST Json Object as a Model using fiddler

Post Body = { “ProductName”=”Apple”, “Price”=”22”}



Exercise 6: POST Form data using fiddler

Change the content type

  • Content-type: application/x-www-form-urlencoded

Change Request body

  • Name=’Apple’&Price=’22’


Exercise 7: PUT (update) Json string using fiddler



Exercise 8: DELETE using fiddler

Note: body part is not applicable for DELETE.



Summary

Now, we have a basic idea about Web API, how to start a project, understanding existing sample code when a Web API project is created, and how to call HTTP methods of Api Controller.

In the Next Blog we will see how can we can work with custom methods on API Controller.

References:

http://www.w3schools.com/tags/ref_httpmethods.asp

http://blogs.microsoft.co.il/idof/2012/03/05/wcf-or-aspnet-web-apis-my-two-cents-on-the-subject/

Leave a comment »