ASP.NET Core Web API 開發-RESTful API實現

來源:互聯網
上載者:User

標籤:

ASP.NET Core Web API 開發-RESTful API實現

REST 介紹:

符合REST設計風格的Web API稱為RESTful API。

具象狀態傳輸(英文:Representational State Transfer,簡稱REST)是Roy Thomas Fielding博士於2000年在他的博士論文 "Architectural Styles and the Design of Network-based Software Architectures" 中提出來的一種全球資訊網軟體架構風格。

目前在三種主流的Web服務實現方案中,因為REST模式與複雜的SOAP和XML-RPC相比更加簡潔,越來越多的web服務開始採用REST風格設計和實現。例如,Amazon.com提供接近REST風格的Web服務執行圖書查詢;雅虎提供的Web服務也是REST風格的。

符合REST設計風格的Web API稱為RESTful API。它從以下三個方面資源進行定義:

直觀簡短的資源地址:URI,比如:http://example.com/resources/。
傳輸的資源:Web服務接受與返回的互連網媒體類型,比如:JSON,XML,YAML等。
對資源的操作:Web服務在該資源上所支援的一系列要求方法(比如:POST,GET,PUT或DELETE)。

 

PUT和DELETE方法是等冪方法。GET方法是安全方法(不會對伺服器端有修改,因此當然也是等冪的)。

不像基於SOAP的Web服務,RESTful Web服務並沒有“正式”的標準。這是因為REST是一種架構,而SOAP只是一個協議。雖然REST不是一個標準,但大部分RESTful Web服務實現會使用HTTP、URI、JSON和XML等各種標準。

實現舉例

例如,一個簡單的網路商店應用,列舉所有商品,

GET http://www.store.com/products

呈現某一件商品,

GET http://www.store.com/product/12345

下單購買,

POST http://www.store.com/order<purchase-order>  <item> ... </item></purchase-order>

 

常用的HTTP動詞有下面五個(括弧裡是對應的SQL命令)

  • GET(SELECT):從伺服器取出資源(一項或多項)。
  • POST(CREATE):在伺服器建立一個資源。
  • PUT(UPDATE):在伺服器更新資源(用戶端提供改變後的完整資源)。
  • PATCH(UPDATE):在伺服器更新資源(用戶端提供改變的屬性)。
  • DELETE(DELETE):從伺服器刪除資源。

下面我們就來在ASP.NET Core Web API 中實現。

例子以使用者為例,對使用者的各個更改分別對應不同的HTTP 動詞。

首先我們建立一個ASP.NET Core Web API 應用程式。可以參考之前博文: http://www.cnblogs.com/linezero/p/5497472.html

然後我們添加EF Core,來操作資料庫。EF Core 教程:http://www.cnblogs.com/linezero/p/EntityFrameworkCore.html

首先我們來建立一個類 User.cs 

    public class User    {        public int Id { get; set; }        public string UserName { get; set; }        public string Password { get; set; }    }

 

然後添加EF Core引用及建立DataContext.cs,並做配置。

EF Core 1.0 已經發布了,所以引用及配置都可以更新一下。

Install-Package Microsoft.EntityFrameworkCore.Sqlite

配置對應做更新

Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
  "tools": {    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",

最後使用dotnet ef 命令來建立資料庫。

  dotnet ef migrations add MyFirstMigration  dotnet ef database update

 

下面就來正式Web API 的開發。

這裡我們添加一個Web API 控制器 UsersController 。

會預設為我們產生GET POST PUT DELETE 對應的方法。這裡我們就來具體實現。

UsersController.cs

    [Route("api/[controller]")]    public class UsersController : Controller    {        private DataContext Context;        public UsersController(DataContext _context)        {            Context = _context;        }        // GET: api/users        [HttpGet]        public IActionResult Get()        {            return Ok(Context.Users.ToList());        }        // GET api/users/5        [HttpGet("{id}")]        public IActionResult Get(int id)        {            var _user = Context.Users.FirstOrDefault(r => r.Id == id);            if (_user == null)                return NotFound();            return Ok(_user);        }        // POST api/users        [HttpPost]        public IActionResult Post([FromBody]User user)        {            Context.Add(user);            Context.SaveChanges();            return Created($"api/users/{user.Id}",user);        }        // PUT api/users/5        [HttpPut("{id}")]        public IActionResult Put(int id, [FromBody]User user)        {            var _user = Context.Users.FirstOrDefault(r => r.Id == id);            if (_user == null)                return NotFound();            _user.UserName = user.UserName;            _user.Password = user.Password;            Context.Update(_user);            Context.SaveChanges();            return Created($"api/users/{_user.Id}", _user);        }        // DELETE api/users/5        [HttpDelete("{id}")]        public IActionResult Delete(int id)        {            var _user = Context.Users.FirstOrDefault(r => r.Id == id);            if (_user == null)                return NotFound();            Context.Remove(_user);            Context.SaveChanges();            return NoContent();        }    }

實現好以後,我們使用Chrome 應用 ARC 來調試。

增加-》Post:

{"Id":1,"UserName":"LineZero","PassWord":"123456"}

 http://localhost:5000/api/users

多個查詢-》Get:

 http://localhost:5000/api/users

單個查詢-》Get(int id):

 http://localhost:5000/api/users/1

修改-》Put:

{"UserName":"LineZeroASPNETCore","PassWord":"123456789"}

 http://localhost:5000/api/users/1

刪除-》Delete:

 http://localhost:5000/api/users/1

 

 

對應的Http 操作也都實現了。資料庫相關操作也在代碼裡。

對於ASP.NET Core Web API REST 風格的一種代碼實現。

 

ASP.NET Core Web API 預設JSON序列化的話,會將屬性名稱自動轉化為小寫,這裡我們只需要一句配置即可解決。

        public void ConfigureServices(IServiceCollection services)        {            // Add framework services.            services.AddMvc().AddJsonOptions(r=>r.SerializerSettings.ContractResolver= new Newtonsoft.Json.Serialization.DefaultContractResolver());        }

 

本文範例程式碼:https://github.com/linezero/Blog/tree/master/ASPNETCoreAPI

 

參考連結:

https://zh.wikipedia.org/wiki/REST

http://www.ruanyifeng.com/blog/2014/05/restful_api.html

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

ASP.NET Core Web API 開發-RESTful 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.