ASP.NET 5系列教程 (六): 在 MVC6 中建立 Web API

來源:互聯網
上載者:User

標籤:

ASP.NET 5.0 的主要目標之一是統一MVC 和 Web API 架構應用。

接下來幾篇文章中您會瞭解以下內容:

  • ASP.NET MVC 6 中建立簡單的web API。

  • 如何從空的項目模板中啟動,及添加控制項到應用中。

  • 如何配置 ASP.NET 5.0 管道。

  • 在 IIS 外對立部署應用。

本文的目的是從空的項目開始,逐步講解如何建立應用。當然,您也可以從“Starter Web” 模板開始,它預設包含了MVC 6、許可權、記錄等其他模組,同時也內建了有效控制器和視圖在其中。

建立空的 ASP.NET 5 項目

開啟 Visual Studio 2015。點擊 File 菜單,選擇 New > Project。

New Project 對話方塊中,點擊 Templates > Visual C# > Web,選擇 ASP.NET Web Application 項目模板。命名為 "TodoApi",點擊 OK。

New ASP.NET Project 對話方塊中,選擇 "ASP.NET 5.0 Empty" 模板。

下面的展示了工程結構:

工程包含以下檔案:

  • global.json 包含瞭解決方案層級的設定,允許工程到工程之間的引用。

  • project.json 包含了工程層級的設定。

  • Project_Readme.html  為 readme 檔案。

  • Startup.cs 包含啟動和配置代碼。

Startup.cs 檔案中的Startup 類,配置了 ASP.NET 需求管道。當你使用空的項目模板,Startup 類不會有任何實質性的代碼加入到管道中:

  Startup
{
     void Configure(IApplicationBuilder app)
    {
        //  here!
    }
}

 

現在,你可以運行應用了,但當前的應用沒有任何功能。接下來我們會類比"Starter Web" 項目模板來添加功能,例如 MVC 6、Entity Framework、身分識別驗證、記錄等功能。

添加歡迎介面

開啟 project.json 檔案。該檔案包含了工程設定內容。dependencies 部分用於標註需要的NuGet 包和類庫。添加 Microsoft.AspNet.Diagnostics 包到列表中:

"": {
    "": "",
    // Add this:
    "": ""
},

 

輸入時, Visual Studio 會提供智能提示:

接下來,開啟 Startup.cs 檔案,添加以下代碼:

 System;
 Microsoft.AspNet.Builder;
 
 
 TodoApi
{
      Startup
    {
         void Configure(IApplicationBuilder app)
        {
            //  code
            app.UseWelcomePage();
        }
    }
}

 

點擊  F5 運行,Visual Studio 啟動瀏覽器,開啟了 http://localhost:port/,連接埠號碼是一個Visual Studio隨機分配的數字。運行效果如下:

歡迎介面是檢驗運行效果的快速入口,無需編寫代碼。

建立 Web API

 

在本章節中,您將建立一個 ToDo 事項管理列表功能API。首先,我們需要添加 ASP.NET MVC 6 到應用中。

添加 MVC 6 到 project.json 檔案的依賴列表中:

"": {
    "": "",
    "": "",
    // :
    "": ""
},

 

接下來,添加 MVC 需求管道到 Startup.cs 檔案中,

  • 使用 using 聲明Microsoft.Framework.DependencyInjection。

  • 添加以下方法到 Startup 類中。

 void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

 

  • 下面這段代碼添加了 MVC 6 需要的所有依賴項,會自動在啟動時調用ConfigureServices

     void Configure(IApplicationBuilder app)
    {
        // :
        app.UseMvc();
    }

     

    以下是完整的 Startup 類代碼:

     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();
            }
        }
    }

     

    添加 Model

    model 代表應用的資料域。在本樣本中,model 中儲存 ToDo 項。 添加以下類到項目中:

     System.ComponentModel.DataAnnotations;
     TodoApi.Models
    {
          TodoItem
        {
             int Id { ; ; }
            [Required]
              Title { ; ; }
             bool IsDone { ; ; }
        }
    }

     

    為了保持項目的整潔,我建立了 Models 檔案夾用於存放 Model 類,當然這不是必要的操作。

    添加 Controller

    添加 controller 類用於處理 HTTP 要求。添加以下類到項目中:

     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
            }
        }
    }

     

    同樣,我建立了 Controllers 檔案夾用於儲存 controller。

    在後續的章節中我們將進一步闡述關於 Controller 的代碼。以下是 controller 實現的一些基礎功能:

    例如,下面是擷取 ToDo 項目的 HTTP 要求的:

     http://localhost:5000/api/todo HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:5000

     

    下面是 response 流:

    HTTP/1.1 200 OK
    Content-Type: application/json;charset=utf-8
    Server: Microsoft-HTTPAPI/2.0
    : Thu, 30 Oct 2014 22:40:31 GMT
    Content-Length: 46
    [{"":1,"":"","":}]

    後續章節中我們將闡述以下內容:

    • 在配置方法中添加以下代碼,UseMvc 方法用於添加 MVC 6 到管道。

  • 如何配置 ASP.NET 5.0 管道。

  • 在 IIS 外對立部署應用。

     

    原文連結:Create a Web API in MVC 6

 

系列文章目錄:
  • ASP.NET 5系列教程 (一):領讀新特性

  • ASP.NET 5系列教程 (二):Hello World

  • ASP.NET 5系列教程 (三):view components介紹

  • ASP.NET 5系列教程 (四):向視圖中添加服務和發布應用到公用雲端

  • ASP.NET 5系列教程 (五):在Visual Studio 2015中使用Grunt、Bower開發Web程式

ASP.NET 5系列教程 (六): 在 MVC6 中建立 Web API

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.