日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core 1.0开发Web API程序

發布時間:2023/12/18 asp.net 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core 1.0开发Web API程序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

.NET Core版本:1.0.0-rc2
Visual Studio版本:Microsoft Visual Studio Community 2015 Update 2
開發及運行平臺:Windows 7 專業版 Service Pack 1 x64

步驟一、創建ASP.NET Core Web API項目

?

?VS里面新建項目,Web-->ASP.NET Core Web Application(.NET Core)-->Web API,比如本例中建立的TodoApi項目。

步驟二、在Models文件夾中新建實體、接口及服務倉庫

TodoItem.cs(實體類)

1 namespace TodoApi.Models 2 { 3 public class TodoItem 4 { 5 public string Key { get; set; } 6 public string Name { get; set; } 7 public bool IsComplete { get; set; } 8 } 9 }

?

?ITodoRepository.cs(接口類)

1 using System.Collections.Generic; 2 3 namespace TodoApi.Models 4 { 5 public interface ITodoRepository 6 { 7 void Add(TodoItem item); 8 IEnumerable<TodoItem> GetAll(); 9 TodoItem Find(string key); 10 TodoItem Remove(string key); 11 void Update(TodoItem item); 12 } 13 }

?TodoRepository.cs(接口實現類,服務的具體實現)

1 using System; 2 using System.Collections.Concurrent; 3 using System.Collections.Generic; 4 5 namespace TodoApi.Models 6 { 7 public class TodoRepository : ITodoRepository 8 { 9 static ConcurrentDictionary<string, TodoItem> _todoItems = new ConcurrentDictionary<string, TodoItem>(); 10 11 public TodoRepository() 12 { 13 Add(new TodoItem() {Name = "Item1"}); 14 } 15 16 public void Add(TodoItem item) 17 { 18 item.Key = Guid.NewGuid().ToString(); 19 _todoItems[item.Key] = item; 20 } 21 22 public IEnumerable<TodoItem> GetAll() 23 { 24 return _todoItems.Values; 25 } 26 27 public TodoItem Find(string key) 28 { 29 TodoItem item; 30 _todoItems.TryGetValue(key, out item); 31 return item; 32 } 33 34 public TodoItem Remove(string key) 35 { 36 TodoItem item; 37 _todoItems.TryGetValue(key, out item); 38 _todoItems.TryRemove(key, out item); 39 return item; 40 } 41 42 public void Update(TodoItem item) 43 { 44 _todoItems[item.Key] = item; 45 } 46 } 47 }

步驟三、在Controllers文件夾中新增Controller類

1 using System.Collections.Generic; 2 using Microsoft.AspNetCore.Mvc; 3 using TodoApi.Models; 4 5 namespace TodoApi.Controllers 6 { 7 [Route("api/[controller]")] 8 public class TodoController : Controller 9 { 10 private ITodoRepository TodoItems { get; set; } 11 12 public TodoController(ITodoRepository todoRepository) 13 { 14 TodoItems = todoRepository; 15 } 16 17 [HttpGet] 18 public IEnumerable<TodoItem> GetAll() 19 { 20 return TodoItems.GetAll(); 21 } 22 23 [HttpGet("{id}", Name = "GetTodo")] 24 public IActionResult GetById(string id) 25 { 26 var item = TodoItems.Find(id); 27 if (item == null) 28 { 29 return NotFound(); 30 } 31 return new ObjectResult(item); 32 } 33 34 [HttpPost] 35 public IActionResult Create([FromBody] TodoItem todoItem) 36 { 37 if (null == todoItem) 38 { 39 return BadRequest(); 40 } 41 TodoItems.Add(todoItem); 42 return CreatedAtRoute("GetTodo", new {controller = "todo", id = todoItem.Key}, todoItem); 43 } 44 45 public IActionResult Update(string id, [FromBody] TodoItem item) 46 { 47 if (item == null || item.Key != id) 48 { 49 return BadRequest(); 50 } 51 var todo = TodoItems.Find(id); 52 if (todo == null) 53 { 54 return NotFound(); 55 } 56 TodoItems.Update(item); 57 return new NoContentResult(); 58 } 59 60 public void Delete(string id) 61 { 62 TodoItems.Remove(id); 63 } 64 } 65 }

?在ASP.NET Core 1.0帶來的新特性這篇文章中有提到ASP.NET Core已經把MVC和Web API整合到一起了,所以我們看到Controller類引用的是Microsoft.AspNetCore.Mvc這個NuGet包了,從字面上也可以看出這個整合。

步驟四、編寫用于啟動應用的主入口程序

progrom.cs

1 using System.IO; 2 using Microsoft.AspNetCore.Hosting; 3 4 namespace TodoApi 5 { 6 public class Program 7 { 8 public static void Main(string[] args) 9 { 10 var host = new WebHostBuilder() 11 .UseKestrel() // 使用Kestrel服務器 12 .UseContentRoot(Directory.GetCurrentDirectory()) // 指定Web服務器的對應的程序主目錄 13 .UseStartup<Startup>() // 指定Web服務器啟動時執行的類型,這個約定是Startup類 14 .Build(); // 生成Web服務器 15 host.Run(); // 運行Web應用程序 16 } 17 } 18 }

步驟五、Startup類型實現

Startup.cs(這個是約定的啟動應用時加載執行的類型,約定包括:類型的名稱,自動生成的相關類方法)

1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.AspNetCore.Hosting; 3 using Microsoft.Extensions.Configuration; 4 using Microsoft.Extensions.DependencyInjection; 5 using Microsoft.Extensions.Logging; 6 using TodoApi.Models; 7 8 namespace TodoApi 9 { 10 public class Startup 11 { 12 public Startup(IHostingEnvironment env) 13 { 14 var builder = new ConfigurationBuilder() 15 .SetBasePath(env.ContentRootPath) 16 .AddJsonFile("appsettings.json", true, true) 17 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true) 18 .AddEnvironmentVariables(); 19 Configuration = builder.Build(); 20 } 21 22 public IConfigurationRoot Configuration { get; } 23 24 // This method gets called by the runtime. Use this method to add services to the container. 25 public void ConfigureServices(IServiceCollection services) 26 { 27 // Add framework services. 28 services.AddMvc(); 29 30 // Add our respository type 31 services.AddSingleton<ITodoRepository, TodoRepository>(); 32 } 33 34 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 35 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 36 { 37 loggerFactory.AddConsole(Configuration.GetSection("Logging")); 38 loggerFactory.AddDebug(); 39 40 app.UseMvc(); 41 } 42 } 43 }

Startup構造函數里面主要是初始化配置,應用的配置可以是外部自定義的JSON文件,比如本例中的appsettings.json,我們甚至可以根據不同的環境(FAT,UAT,PRD等)生成給自環境使用的配置文件,比如:

appsettings.FAT.json、appsettings.UAT.json等,不同的環境根據環境變量{env.EnvironmentName}配置的值來讀取相應的配置文件。這個{env.EnvironmentName}可以通過項目的Properties下的launchSettings.json文件進行配置,如下:

1 { 2 "TodoApi": { 3 "commandName": "Project", 4 "launchBrowser": true, 5 "launchUrl": "http://localhost:5000/api/todo", 6 "environmentVariables": { 7 "ASPNETCORE_ENVIRONMENT": "PRD" 8 } 9 } 10 } 11 }

?ConfigureServices,Configure方法的作用在在ASP.NET Core 1.0帶來的新特性這篇文章中已有闡述,這里不再贅述。

步驟六、運行程序

在cmd里面把當前目錄切換到項目的根目錄,然后依次執行后面的命令:1、dotnet restore?2、dotnet build?3、dotnet run

執行完dotnet run后,應用程序已經啟動起來了,通過控制臺的輸出提示可以看出,Web服務器在5000端口偵聽請求。

測試一個URL(http://localhost:5000/api/todo):

控制臺輸出info日志:

我們也可以改變控制臺輸出日志的級別,只需要更改我們自定義的appsettings.json配置即可,如下:

1 { 2 "Logging": { 3 "IncludeScopes": false, 4 "LogLevel": { 5 "Default": "Debug", 6 "System": "Debug", 7 "Microsoft": "Warning" 8 } 9 } 10 }

把“Microsoft”的值改成:“Warning”,這樣上述info級別的日志就不會再輸出了(Warning,Error級別的日志才會輸出)。

?

轉載于:https://www.cnblogs.com/frankyou/p/5594557.html

總結

以上是生活随笔為你收集整理的ASP.NET Core 1.0开发Web API程序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。