Web Services : Useful Links to get started

There are a few things confounding me in my understanding of WebService development in C#

 

  1. Return types from action methods.

Two very interesting reads :

 

Return Type Example / Comments
1.ActionResult.

 

  • return Content(“AmlRequestResponse task not in state IsCompleted!”);
  • return this.Content(jsonString);
    
  • This is MVC specific
2.Product / IEnumerable<Product>
  • return products;
  • What’s the difference between this and using IHttpActionResult
3.IHttpActionResult
  • return Ok(product);
4.HttpResponseMessage
  • return Request.CreateResponse(HttpStatusCode.OK);
  • return Request.CreateResponse(HttpStatusCode.OK,
    response,
    JsonMediaTypeFormatter.DefaultMediaType);
5.String / async Task<string>
  • return “abhishek”;

 

  • For 2,3,4 if we return objects, then we get JSON response back
  • If we say return Ok(“bob”) then string “bob” gets returned.

 

  1. Routing By Verb

 

  • By default Web API chooses controller actions based on an HTTP Verb (RESTful approach). You can force it into an RPC mode (action name based), but you can’t combine these two in a single controller, and as it would throw an Ambiguous match exception.

 

  • To determine which action to invoke, the framework uses a routing table. The Visual Studio project template for Web API creates a default route:

routes.MapHttpRoute(
name: “API Default”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);

 

  • Each entry in the routing table contains a route template. The default route template for Web API is “api/{controller}/{id}”. In this template, “api” is a literal path segment, and {controller} and {id} are placeholder variables.

 

  • When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table. If no route matches, the client receives a 404 error. For example, the following URIs match the default route:
    • /api/contacts
    • /api/contacts/1
    • /api/products/gizmo1

 

  • Once a matching route is found, Web API selects the controller and the action:
    • To find the controller, Web API adds “Controller” to the value of the {controller} variable.
    • To find the action, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with “Get…”, such as “GetContact” or “GetAllContacts”.  This convention applies only to GET, POST, PUT, and DELETE methods. It pretty much looks for anything starting with ‘Get..’ that matches the parameters passed
    • You can enable other HTTP methods by using attributes on your controller. We’ll see an example of that later.
    • Other placeholder variables in the route template, such as {id}, are mapped to action parameters.

 

  • Example #1. Suppose that you define the following controller:

public class ProductsController : ApiController
{
public void GetAllProducts() { }
public IEnumerable<Product> GetProductById(int id) { }
public HttpResponseMessage DeleteProduct(int id){ }
}

Here are some possible HTTP requests, along with the action that gets invoked for each:

HTTP Method URI Path Action Parameter
GET api/products GetAllProducts (none)
GET api/products/4 GetProductById 4
DELETE api/products/4 DeleteProduct 4
POST api/products (no match)

Notice that the {id} segment of the URI, if present, is mapped to the id parameter of the action. In this example, the controller defines two GET methods, one with an id parameter and one with no parameters.

Also, note that the POST request will fail, because the controller does not define a “Post…” method.

 

  • Example #2. Let’s say you’ve created a new subclass of ApiController called OrderController. WebAPI provides your OrderController with out-of-the-box support for the following URLs:

 

HTTP VERB URL DESCRIPTION
GET /api/order Returns all orders
GET /api/order/3 Returns details order #3
POST /api/order Create new order
PUT /api/order/3 Update order #3
DELETE /api/order/3 Delete order #3

 

The above is considered verb-based routing. The URLs above only contain thecontroller name and an optional id. So the Web API uses the HTTP verb of the request to determine the action method to execute in your ApiController subclass.

 

  1. Routing By Action Name

 

With the default routing template, Web API uses the HTTP method to select the action. However, you can also create a route where the action name is included in the URI:

routes.MapHttpRoute(
name: “ActionApi”,
routeTemplate: “api/{controller}/{action}/{id}”,
defaults: new { id = RouteParameter.Optional });

 

In this route template, the {action} parameter names the action method on the controller. With this style of routing, use attributes to specify the allowed HTTP methods. For example, suppose your controller has the following method:

public class ProductsController : ApiController
{
[HttpGet]
public string Details(int id);
}

In this case, a GET request for “api/products/details/1” would map to the Details method. This style of routing is similar to ASP.NET MVC, and may be appropriate for an RPC-style API.

You can override the action name by using the ActionName attribute. In the following example, there are two actions that map to “api/products/thumbnail/id. One supports GET and the other supports POST:

public class ProductsController : ApiController
{
[HttpGet]
[ActionName(“Thumbnail”)]
public HttpResponseMessage GetThumbnailImage(int id);

[HttpPost]
[ActionName(“Thumbnail”)]
public void AddThumbnailImage(int id);
}

  • Non-Actions

To prevent a method from getting invoked as an action, use the NonAction attribute. This signals to the framework that the method is not an action, even if it would otherwise match the routing rules.

// Not an action method.
[NonAction]
public string GetPrivateData() { … }

 

  1. References:

 

 

[1] http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

[2] http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection   –-> this link describes exactly how the framework matches a URI to a route, selects a controller, and then selects the action to invoke. good read

[3] http://blog.appliedis.com/2013/03/25/web-api-mixing-traditional-verb-based-routing/

[4] http://www.strathweb.com/2013/01/magical-web-api-action-selector-http-verb-and-action-name-dispatching-in-a-single-controller/

[5] http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results

[6] http://thuru.net/2015/02/20/httpresponsemessage-vs-ihttpactionresult/

[7] http://stackoverflow.com/questions/21758615/why-should-i-use-ihttpactionresult-instead-of-httpresponsemessage

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s