Tag Archives: web services

STEP BY STEP INSTRUCTION FOR BUILDING RESTFUL API WITH ASP.NET WEB API – PART II

Register the repository

when install the ninject packages, it will create a file NinjectWebCommon.cs  under the App_Start foler, open it, go the method: RegisterServices, register your service.


  private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind().To().InSingletonScope();
            kernel.Bind().To().InSingletonScope();
        }     

what is this do, you don’t need new a object, instead of the ninject container will create a instance in your controller or repositaory class. And the ninject also will handle the life cycle of the object.

Create  MovieDataViewModal.cs file under the ViewModal foler, we using it for validation and create and put Movie record.


  using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MovieDemo.ViewModal
{
    public class MovieDataViewModal : IValidatableObject
    {
        public int MovieId { get; set; }
        [Required]
        [Remote("DoesTitleExist", "Movies")]
        public string Title { get; set; }
        [Required]
        public string Genre { get; set; }
        [Required]
        public string Classification { get; set; }
        [Range(0, 5)]
        public int Rating { get; set; }
        public int ReleaseDate { get; set; }
        public string[] Cast { get; set; }

        public IEnumerable Validate(ValidationContext validationContext)
        {
            var result = new List();

            if (Title == Genre)
            {
                result.Add(new ValidationResult("Title can not be the same as your Genre", new string[] { "Title" }));
            }
            return result;
        }
    }
}

In the Global.asax add the config for using Automap


Mapper.Initialize(config =>
            {
                config.CreateMap<MovieData, MovieDataViewModal>().ReverseMap();
            });

Create the controller

In the solution explorer, create MoviesController.cs undert the Controllers foler


using System;
using System.Web.Http;
using MoviesLibrary;
using System.Web.Http.OData;
using MovieDemo.Services;
using AutoMapper;
using MovieDemo.ViewModal;

namespace MovieDemo.Controllers
{
    public class MoviesController : ApiController
    {
        private readonly IDataRepository _repo;

        public MoviesController(IDataRepository dataRepository)
        {
            _repo = dataRepository;
        }

       
        [EnableQuery(PageSize = 5)]// this is for suport url query working with oData
        public IHttpActionResult Get()
        {
            try
            {
                var movies = _repo.GetAllMovies(); 
                return Ok(movies);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }
    

        //GET: api/Movies/5
        public IHttpActionResult Get(int id)
        {
            try
            {
                if (id > 0)
                {
                    var movie = _repo.GetMovieById(id);
                    var result = Mapper.Map(movie);
                    if (result != null) return Ok(result);

                    return NotFound();
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // POST: api/Movies 
        public IHttpActionResult Post([FromBody]MovieDataViewModal newMovie) 
        {
            try
            {

                if (newMovie == null)
                    return BadRequest("Movie can not be null");

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var movie = Mapper.Map(newMovie);

                if (_repo.CreateMovie(movie)) return Ok(newMovie);

                return Conflict();

            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // PUT : api/Movies/5
        public IHttpActionResult Put(int id, [FromBody]MovieDataViewModal movieModified)
        {
            try
            {

                if (movieModified == null)
                    return BadRequest("Movie can not be null");

                if (movieModified.MovieId <= 0 && movieModified.MovieId != id)
                    return Conflict();

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var movieData = _repo.GetMovieById(id);
                if (movieData != null)
                {
                    var movie = Mapper.Map(movieModified);
                    _repo.UpdateMovie(movie); 
                    return Ok();
                }

                return NotFound();

            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }

        public IHttpActionResult DoesTitleExist(string title)
        {
            if (_repo.DoesTitleAlreadyExist(title))
            {
                //Invalid
                return Ok();
            }
            //Valid
            return BadRequest("Title already existing");
        }
    }
}

then run the solution, open postman make query:

here is the example: http://localhost:53871/api/movies?$skip=2&$top=1
api06.PNG

for allmovies: api05.PNG

more detail  about odata query:
http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
Advertisements