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.

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

The following shows the engineering structure:

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",
    
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta1"
},

When you enter, Visual Studio provides smart hints:

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:

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 .

      • Add the following code to the configuration method to UseMvc add MVC 6 to the pipeline.
     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 Get set; }
            [Required]
             Public string Get set; }
             Public 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 New List<todoitem> ()
            {
                New TodoItem {Id = 1, Title = "FirstItem"}
            };
            [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 ("getbyidrouteNew
                        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:

    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": "FirstItem", "IsDone":false}]

    In the following sections we will explain:

  • 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

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.