ASP. NET 5 Series tutorial (vi): Creating a Web API in MVC6

Source: Internet
Author: User

One of the main goals of ASP. NET 5.0 is to unify MVC and WEB API framework applications.

In the next few articles you will find the following:

    • Create a simple Web API in ASP. 6.

    • How to start from an empty project template, and add controls to the app.

    • How to configure an ASP. NET 5.0 pipeline.

    • To deploy apps outside of IIS.

The purpose of this article is to start with an empty project and step through how to create an app. Of course, you can also start with the Starter Web template, which includes MVC 6, permissions, records and other modules by default, as well as a built-in controller and view.

Create an empty ASP. NET 5 Project

Open Visual Studio 2015. Click the File menu and select New > Project.

In the New Project dialog box, click Templates > Visual C # > Web, select the ASP. NET Web Application project module Plate. Name "Todoapi" and click OK.

650) this.width=650; "Width=" height= "src=" http://i1.asp.net/media/5135657/webapi04.png?cdn_id= 2015-01-19-002 "/>

In the New ASP . NET Project dialog box, select the "ASP. 5.0 Empty" template.

650) this.width=650; "Width=" "height=" 448 "src=" http://i1.asp.net/media/5135723/webapi15.png?cdn_id= 2015-01-19-002 "/>

The following shows the engineering structure:

650) this.width=650; "src=" http://i3.asp.net/media/5135717/webapi14.png?cdn_id=2015-01-19-002 "/>

The project contains the following files:

    • Global.json contains the solution-level settings that allow references between projects to engineering.

    • Project.json contains the project-level settings.

    • Project_readme.html is a Readme file.

    • Startup.cs contains the startup and configuration code.

The classes in the Startup.cs file are configured with the Startup ASP. NET requirements pipeline. When you use an empty project template, the Startup class does not have any substantive code to add to the pipeline:

public class Startup
{
public void Configure (Iapplicationbuilder app)
{
Nothing here!
}
}

Now you can run the app, but the current app doesn't have any functionality. Next we'll emulate the Starter Web project template to add features such as MVC 6, Entity Framework, authentication, logging, and more.

Add Welcome screen

Open the Project.json file. This file contains the project setup content. dependenciessections are used to annotate 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 you enter, Visual Studio provides smart hints:

650) this.width=650; "src=" http://i2.asp.net/media/5135663/webapi05.png?cdn_id=2015-01-19-002 "/>

650) this.width=650; "src=" http://i3.asp.net/media/5135669/webapi06.png?cdn_id=2015-01-19-002 "/>

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 Run, Visual Studio launches the browser, opens the http://localhost:Port/, port number is a randomly assigned number in Visual Studio. The results are as follows:

650) this.width=650; "Width=" "height=" 346 "src=" http://i2.asp.net/media/5135729/webapi16.png?cdn_id= 2015-01-19-002 "/>

The welcome interface is a quick entry for verifying the effect of a run without writing code.

Create a Web API

In this section, you will create a ToDo Item Management list feature API. First, we need to add ASP. NET MVC 6 to the app.

Add the 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 requirements pipeline to the Startup.cs file,

    • Use a using declarationMicrosoft.Framework.DependencyInjection。

    • Add the following methods to the Startup class.

public void Configureservices (iservicecollection services)
{
Services. Addmvc ();
}

  • The following code adds all the dependencies required by MVC 6 and is automatically invoked at startup ConfigureServices .

    public void Configure (Iapplicationbuilder app)
    {
    New:
    App. Usemvc ();
    }

    The following is the complete Startup 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 Model

    model represents the data field of the application. In this example, a ToDo item is stored in 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 neat, I created the Models folder for the Model class, which is not a necessary operation, of course.

    Add Controller

    Add a controller class to handle 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 the subsequent chapters we will further elaborate on the Controller's code. The following are some of the basic functions that the controller implements:

    650) this.width=650; "Width=" 610 "height=" 241 "title=" image "style=" border-width:0px; "alt=" image "src=" http:/ Images.cnitblog.com/blog/139239/201502/050938002963700.png "border=" 0 "/>

    For example, here's an HTTP request to get a ToDo project:

    GET 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
    Date:thu, Oct 22:40:31 GMT
    content-length:46

    [{"Id": 1, "Title": "First Item", "IsDone": false}]

    In the following sections we will explain:

      • Add the following code to the configuration method to UseMvc add MVC 6 to the pipeline.

  • How to configure an ASP. NET 5.0 pipeline.

  • To deploy apps outside of IIS.

    Original link: Create a Web API in MVC 6

Series Articles Directory:
    • ASP. 5 Series Tutorial (i): bribed new features

    • ASP. 5 Series Tutorial (ii): Hello World

    • ASP 5 Series Tutorial (iii): View Components Introduction

    • ASP. NET 5 Series tutorial (iv): adding services and publishing to a view apply to public cloud

    • ASP. NET 5 Series tutorial (V): Developing Web Programs using Grunt, bower in Visual Studio 2015


This article is from the "Grape City Control Technology Team Blog" blog, be sure to keep this source http://powertoolsteam.blog.51cto.com/2369428/1611791

ASP. NET 5 Series tutorial (vi): Creating a Web API in MVC6

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.