ASP. NET 5 Series tutorial (6): create a Web API in MVC6, asp. netmvc6
One of the main goals of ASP. NET 5.0 is to unify MVC and Web API framework applications.
In the following articles, you will understand the following:
- Create a simple web API in ASP. net mvc 6.
- How to start from an empty project template and add controls to the application.
- How to configure an ASP. NET 5.0 pipe.
- Deploy applications outside of IIS.
The purpose of this article is to explain how to create an application step by step from an empty project. Of course, you can also start with the "Starter Web" template. By default, it contains MVC 6, permissions, records, and other modules. It also has built-in effective controllers and views.
Create an empty ASP. NET 5 Project
Open Visual Studio 2015. ClickFileMenu, selectNew>Project.
InNew ProjectIn the dialog box, clickTemplates>Visual C #>Web, selectASP. NET Web Application project template. Name it "TodoApi" and click OK.
InNew ASP. NET ProjectIn the dialog box, select the "ASP. NET 5.0 Empty" template.
The following shows the engineering structure:
The project contains the following files:
- Global. json contains solution-level settings that allow reference between projects.
- Project. json contains project-level settings.
- Project_Readme.html is a readme file.
- Startup. cs contains the Startup and configuration code.
In the Startup. cs fileStartup
Class, configured ASP. NET demand pipeline. When you use an empty project template,Startup
The class will not have any substantive code added to the pipeline:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// Nothing here!
}
}
Now you can run the application, but the current application does not have any function. Next, we will simulate the "Starter Web" Project template to add functions, such as MVC 6, Entity Framework, authentication, record and other functions.
Add welcome page
Open the project. json file. This file contains the project settings.dependencies
Some are used to mark the required NuGet packages and class libraries. Add the Microsoft. AspNet. Diagnostics package to the list:
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
// Add this:
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1"
},
When entered, Visual Studio provides a smart prompt:
Next, open the Startup. cs file and add the following code:
using System;
using Microsoft.AspNet.Builder;
namespace TodoApi
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// New code
app.UseWelcomePage();
}
}
}
Click F5 to run. Visual Studio starts the browser and opens http: // localhost:Port/, The port number is a random number assigned by Visual Studio. The running effect is as follows:
The welcome interface is a quick entry to verify the running effect without writing code.
Create a Web API
In this section, you will create a ToDo Event Management list API. First, we need to add ASP. net mvc 6 to the application.
Add MVC 6 to the dependency list of the project. json file:
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
// New:
"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
Next, add the MVC requirement pipeline to the Startup. cs file,
- Use using Declaration
Microsoft.Framework.DependencyInjection。
- Add the following method
Startup
Class.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
The following code adds all the dependencies required by MVC 6 and is automatically called at startup.ConfigureServices
.
- Add the following code to the configuration method,
UseMvc
The method is used to add MVC 6 to the MPs queue.
public void Configure(IApplicationBuilder app)
{
// New:
app.UseMvc();
}
The following are completeStartup
Class Code:
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
// New using:
using Microsoft.Framework.DependencyInjection;
namespace TodoApi
{
public class Startup
{
// Add this method:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
// New:
app.UseMvc();
app.UseWelcomePage();
}
}
}
Add ModelModelThe data domain of the application. In this example, the ToDo item is stored in the model. Add the following classes to the project:
using System.ComponentModel.DataAnnotations;
namespace TodoApi.Models
{
public class TodoItem
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public bool IsDone { get; set; }
}
}
To keep the project clean and tidy, I created the Models folder to store the Model class. Of course this is not necessary.
Add ControllerAddControllerClass is used to process HTTP requests. Add the following classes to the project:
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using System.Linq;
using TodoApi.Models;
namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
static readonly List<TodoItem> _items = new List<TodoItem>()
{
new TodoItem { Id = 1, Title = "First Item" }
};
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
return _items;
}
[HttpGet("{id:int}", Name = "GetByIdRoute")]
public IActionResult GetById (int id)
{
var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null)
{
return HttpNotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public void CreateTodoItem([FromBody] TodoItem item)
{
if (!ModelState.IsValid)
{
Context.Response.StatusCode = 400;
}
else
{
item.Id = 1+ _items.Max(x => (int?)x.Id) ?? 0;
_items.Add(item);
string url = Url.RouteUrl("GetByIdRoute", new { id = item.Id },
Request.Scheme, Request.Host.ToUriComponent());
Context.Response.StatusCode = 201;
Context.Response.Headers["Location"] = url;
}
}
[HttpDelete("{id}")]
public IActionResult DeleteItem(int id)
{
var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null)
{
return HttpNotFound();
}
_items.Remove(item);
return new HttpStatusCodeResult(204); // 201 No Content
}
}
}
Similarly, I created the Controllers folder to store the controller.
In subsequent chapters, we will further elaborate on the Controller code. The following are some basic functions implemented by the controller:
For example, the following is an HTTP request for obtaining the ToDo project:
GET http://localhost:5000/api/todo HTTP/1.1
User-Agent: Fiddler
Host: localhost:5000
Below is the response stream:
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 30 Oct 2014 22:40:31 GMT
Content-Length: 46
[{"Id":1,"Title":"First Item","IsDone":false}]
In subsequent chapters, we will elaborate on the following:
- How to configure an ASP. NET 5.0 pipe.
- Deploy applications outside of IIS.
Original article: Create a Web API in MVC 6
Series of articles:
ASP. NET 5 Series tutorials (1): Reading New Features
ASP. NET 5 Series tutorial (2): Hello World
ASP. NET 5 Series tutorials (III): Introduction to view components
ASP. NET 5 Series tutorial (4): Add services to the view and publish applications to the public cloud
ASP. NET 5 Series tutorial (5): Use Grunt and Bower in Visual Studio 2015 to develop Web programs