Learn how to create a REST API with Attribute Routing in WEB API Part 3

Rama Sagar
Posted by in ASP.NET Web API category on for Beginner level | Points: 250 | Views : 4065 red flag
Rating: 4 out of 5  
 1 vote(s)

According to MSDN, Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing.
In this article we will look into how to create a REST API using Attribute Routing in WEB API 2.

Introduction


In this article, we will use attribute routing to create a REST API for a collection of products.For a general overview of attribute routing, see previous articles Part 1 ,Part 2

Objective

The Objective of the article is to create a REST API using Attribute Routing in WEB API 2



In previous article we have seen the package installation and the context configuration..Lets continue the remaining part


  • Step 1  Now If we run the application now and send a GET request to /api/products/2, the response looks similar to the following. (I added indentation for readability.)


{
"ProductId":2,
"Title":"Xperia",
"Price":14.95,
"Category":"Mobiles",
"ReleaseDate":"2000-12-11T00:00:00"
,"Description":"A Sony Mobile.",
"ManufacturerId":2,
"Manufacturer":null
}


  • Step 2 Lets add the Data Transfer objects

In Solution Explorer, right-click the project and select Add | New Folder. Name the folder "DTOs". Add a class named ProductDto to the DTOs folder, with the following implementation:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProductsAPI.DTOs
{
    public class ProductDtO
    {
        public string Title { get; set; }
        public string Manufacturer { get; set; }
        public string Category { get; set; }
    }
}

Add another class named ProductDetailDto.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProductsAPI.DTOs
{
    public class ProductDetailDto
    {
        public string Title { get; set; }
        public string Category { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Manufacturer { get; set; }
    }
}

Step 3  Update the ProductsController class to return ProductDto instances. We'll use the Queryable.Select method 
to project Product instances to ProductDto instances. Here is the updated code for the controller class. 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using ProductsAPI.Models;
using ProductsAPI.DTOs;
using System.Linq.Expressions;

namespace ProductsAPI.Controllers
{
    public class ProductsController : ApiController
    {
        private ProductsAPIContext db = new ProductsAPIContext();

        // Typed lambda expression for Select() method. 
        private static readonly Expression<Func<Product, ProductDtO>> AsProductDtO =
            x => new ProductDtO
            {
                Title = x.Title,
                Manufacturer = x.Manufacturer.Name,
                Category = x.Category
            };

        // GET api/Products
        public IQueryable<ProductDtO> GetProducts()
        {
            return db.Products.Include(b => b.Manufacturer).Select(AsProductDtO);
        }

        // GET api/Products/5
        [ResponseType(typeof(ProductDtO))]
        public async Task<IHttpActionResult> GetProduct(int id)
        {
            ProductDtO product = await db.Products.Include(b => b.Category)
                .Where(b => b.ProductId == id)
                .Select(AsProductDtO)
                .FirstOrDefaultAsync();
            if (product == null)
            {
                return NotFound();
            }

            return Ok(product);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Now if we run the application and request /api/products/1, the response body should look like this




Conclusion


In this article we have seen how to modify the controller methods to return a data transfer object (DTO) instead of the EF model.In next part we will see how to add Route attributes

Reference

http://www.restapitutorial.com/

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)