Asp.Net Web API with MVC 6

The latest version of Microsoft web technologies Asp.Net 5 and Mvc 6 have very big differences.

You can find some of  this new features below

  • ASP.NET vNext includes new cloud-optimized versions of MVC 6, Web API 3, Web Pages 4, SignalR 3, and Entity Framework 7.
  • Now Mvc has no dependency to System.Web dll.
  • There is a project.json instead of classic global.asax file.
  • There is Ioc container to manage all dependencies
  • Project structure is more modern and have some javascript tools like gulp.
  • Finally all these Microsoft technologies are open source and cross platform, so we are able to develop apps on Linux or Mac.

Now we will build and Web API on MVC 6 structure.

As a first step we will create a project with below settings.

mvc6

Solution Explorer will shown like this

SolutionExplorer

I’ve added Model Folder to Project and TodoItem.cs class with below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace todoApi.Model
{
    public class TodoItem
    {
        public string Key { get; set; }
        public string Name { get; set; }
        public bool IsCompleted { get; set; }
    }
}

ITodoRepository.cs Interface with below code, I’ve added an interface to add as a dependency Injection instead of TodoRepository directly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace todoApi.Model
{
    public interface ITodoRepository
    {
        void Add(TodoItem item);
        IEnumerable<TodoItem> GetAll();
        TodoItem Find(string key);
        TodoItem Remove(string key);
        void Update(TodoItem item);
    }
}

and Implementation of interface TodoRepository.cs under the Model Folder with following code

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;

namespace todoApi.Model
{
    public class TodoRepository :ITodoRepository
    {
        static ConcurrentDictionary<string, TodoItem> _todos = new ConcurrentDictionary<string, TodoItem>();

        public TodoRepository()
        {
            Add(new TodoItem { Name = "Item1" });
            Add(new TodoItem { Name = "Item2" });
            Add(new TodoItem { Name = "Item3" });
            Add(new TodoItem { Name = "Item4" });
        }

        public IEnumerable<TodoItem> GetAll()
        {
            return _todos.Values;
        }

        public void Add(TodoItem item)
        {
            item.Key = Guid.NewGuid().ToString();
            _todos[item.Key] = item;
        }

        public TodoItem Find(string key)
        {
            TodoItem item;
            _todos.TryGetValue(key, out item);
            return item;
        }

        public TodoItem Remove(string key)
        {
            TodoItem item;
            _todos.TryGetValue(key, out item);
            _todos.TryRemove(key, out item);
            return item;
        }

        public void Update(TodoItem item)
        {
            _todos[item.Key] = item;
        }

    }
}

Now we will register repository into the the DI container in Startup.cs file with below code.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<ITodoRepository, TodoRepository>();
        }

As a last step we will create a Todo Controller with below code and we are ready to test

using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using todoApi.Model;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace todoApi.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        [FromServices]
        public ITodoRepository TodoItems { get; set; }
        [HttpGet]
        public IEnumerable<TodoItem> GetAll()
        {
            return TodoItems.GetAll();
        }
        [HttpGet("{id}", Name = "GetTodo")]
        public IActionResult GetById(string id)
        {
            var item = TodoItems.Find(id);
            if (item == null)
            {
                return HttpNotFound();
            }
            return new ObjectResult(item);
        }
        [HttpPost]
        public IActionResult Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                return HttpBadRequest();
            }
            TodoItems.Add(item);
            return CreatedAtRoute("GetTodo", new { controller = "Todo", id = item.Key }, item);
        }
        [HttpPut("{id}")]
        public IActionResult Update(string id, [FromBody] TodoItem item)
        {
            if (item == null || item.Key != id)
            {
                return HttpBadRequest();
            }

            var todo = TodoItems.Find(id);
            if (todo == null)
            {
                return HttpNotFound();
            }

            TodoItems.Update(item);
            return new NoContentResult();
        }
        [HttpDelete("{id}")]
        public void Delete(string id)
        {
            TodoItems.Remove(id);
        }
    }
}

Now API is ready, your solution explorer should be like below image.

FinalSolutionExplorer

You can use Fiddler or Postman to test.I hope tutorial help you. If you have any question about tutorial you can leave a comment.

You can find source code here :https://github.com/hamdiceylan/WebApiWithMvc6

Leave a Reply

Your email address will not be published. Required fields are marked *