The following code adds all the dependencies required by MVC 6 and is automatically invoked at startup ConfigureServices .
void Configure (Iapplicationbuilder app)
{
// :
App. Usemvc ();
}
The following is the complete Startup class code:
System;
Microsoft.AspNet.Builder;
Microsoft.AspNet.Http;
// :
Microsoft.Framework.DependencyInjection;
Todoapi
{
Startup
{
Add This method:
void Configureservices (iservicecollection services)
{
Services. Addmvc ();
}
void Configure (Iapplicationbuilder app)
{
// :
App. Usemvc ();
App. Usewelcomepage ();
}
}
}
Add Modelmodel represents the data field of the application. In this example, a ToDo item is stored in model. Add the following classes to the project:
System.ComponentModel.DataAnnotations;
Todoapi.models
{
TodoItem
{
int Id {;;}
[Required]
Title {;;}
bool IsDone {;;}
}
}
To keep the project neat, I created the Models folder for the Model class, which is not a necessary operation, of course.
Add ControllerAdd a controller class to handle HTTP requests. Add the following classes to the project:
MICROSOFT.ASPNET.MVC;
System.Collections.Generic;
System.Linq;
Todoapi.models;
Todoapi.controllers
{
[Route ("")]
Todocontroller:controller
{
list<todoitem> _items = list<todoitem> ()
{
TodoItem {Id = 1, Title = ""}
};
[HttpGet]
Ienumerable<todoitem> GetAll ()
{
_items;
}
[HttpGet ("", Name = "")]
Iactionresult GetById (int id)
{
var item = _items. FirstOrDefault (x = x.id = = Id);
(item = = NULL)
{
Httpnotfound ();
}
Objectresult (item);
}
[HttpPost]
void Createtodoitem ([frombody] TodoItem Item)
{
(! Modelstate.isvalid)
{
Context.Response.StatusCode = 400;
}
Else
{
Item. Id = 1+ _items. Max (x = (int?) x.id)?? 0;
_items. ADD (item);
url = Url.routeurl ("", {id = Item. Id},
Request.scheme, Request.Host.ToUriComponent ());
Context.Response.StatusCode = 201;
Context.response.headers[""] = URL;
}
}
[Httpdelete ("")]
Iactionresult DeleteItem (int id)
{
var item = _items. FirstOrDefault (x = x.id = = Id);
(item = = NULL)
{
Httpnotfound ();
}
_items. Remove (item);
Httpstatuscoderesult (204); 201 No Content
}
}
}
Similarly, I created the Controllers folder to store the controller.
In the subsequent chapters we will further elaborate on the Controller's code. The following are some of the basic functions that the controller implements:
For example, here's an HTTP request to get a ToDo project:
Http://localhost:5000/api/todo http/1.1
User-agent:fiddler
host:localhost:5000
Here is the response stream:
http/1.1 OK
Content-type:application/json;charset=utf-8
server:microsoft-httpapi/2.0
: Thu, Oct 22:40:31 GMT
content-length:46
[{"": 1, "": "", "":}]
In the following sections we will explain: