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程序相关推荐
- ASP.NET Core 1.0 开发记录
ASP.NET Core 1.0 更新比较快(可能后面更新就不大了),阅读注意时间节点,这篇博文主要记录用 ASP.NET Core 1.0 开发简单应用项目的一些记录,以备查阅. ASP.NET C ...
- Do You Kown Asp.Net Core -- Asp.Net Core 2.0 未来web开发新趋势 Razor Page
Razor Page介绍 前言 上周期待已久的Asp.Net Core 2.0提前发布了,一下子Net圈热闹了起来,2.0带来了很多新的特性和新的功能,其中Razor Page引起我的关注,作为web ...
- 使用 ASP.NET Core Razor 页、Web API 和实体框架进行分页和排序
目录 核心类 数据层 The API Razor页面 如何使用 .NET Core Razor 页.Web API 和实体框架实现分页和排序,以产生良好的性能. 该项目的特点是: 选择页面大小(Pag ...
- 2022年8月10日:使用 ASP.NET Core 为初学者构建 Web 应用程序--使用 ASP.NET Core 创建 Web UI(没看懂需要再看一遍)
ASP.NET Core 支持使用名为 Razor 的本地模板化引擎创建网页. 本模块介绍了如何使用 Razor 和 ASP.NET Core 创建网页. 简介 通过在首选终端中运行以下命令,确保已安 ...
- ASP.NET Core Web Razor Pages系列教程:使用ASP.NET Core创建Razor Pages Web应用程序
ASP .Net Core Razor Pages MySQL Tutorial 本系列教程翻译自微软官方教程,官方教程地址:Tutorial: Create a Razor Pages web ap ...
- 使用VS Code开发.Net Core 2.0 MVC Web应用程序教程之一
好吧,现在我们假设你已经安装好了VS Code开发工具..Net Core 2.0预览版的SDK dotnet-sdk-2.0.0(注意自己的操作系统),并且已经为VS Code安装好了C#扩展(在V ...
- 了解如何使用ASP.NET Core 3.1构建Web应用程序
ASP.NET Core is an open source web-development framework for building web apps on the .NET platform. ...
- 使用VS Code开发.Net Core 2.0 MVC Web应用程序教程之三(配置文件读取)
干了一天的活,还有点时间,给兄弟们写点东西吧. 大家有没有发现一个问题?那就是在.Net Core的MVC项目里面,没有.config文件了!!!同志们,没有config文件了啊,这样搞,我以后要做些 ...
- 用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传...
第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三 ...
最新文章
- linux mysql insert_linux mysql怎么添加数据
- 【pmcaff】其实一直有一个人在默默关注你
- 【白话机器学习】算法理论+实战之关联规则
- mac 系统使用macaca inspector 获取iphone真机应用元素
- VVC为什么首先在印度落地?
- 深度学习(十四)——Softmax详解, 目标检测, RCNN
- 前端学习(3133):react-hello-react之高阶函数
- 线段(信息学奥赛一本通-T1429)
- 用JavaScript获取页面上被选中的文字的技巧
- [转]IT开发工程师的悲哀
- 预测数据时数据类型是object导致报错TypeError: unsupported operand type(s) for -: ‘str‘ and ‘float‘
- C++中字符串转换函数to_string
- html 简单动画效果,HTML-简单动画
- Dollars即时聊天客户端应用源码
- 基于matlab的相关模板图像匹配技术
- hbuilderX连接雷电模拟器
- 我干区块链这一月,见证从风口到“枪口”
- Java 恋爱纪念日(日期问题)
- 扶贫?教育?地铁?这里有跨界也能实现的企业数字化新操作!
- 网络故障诊断的原则[转自www.cnitblog.com/wildon]
热门文章
- java ibatis 获取执行的sql_小程序官宣+JAVA 三大框架基础面试题
- linux 怎么重装libaprutil,Apache安装出错_cannot install `libaprutil-1.la' to a directory
- 2021CCPC河北省省赛F题(河南省CCPC测试赛重现)
- java的应用程序开发_开发一个Java应用程序(1)
- python duplicated函数_Python DataFrame使用drop_duplicates()函数去重(保留重复值,取重复值)...
- Java学习规划及就业规划(本人大三)
- 替换某个字符串_Schema技术(四)-字符串数据类型
- linux消息类型,heartbeat消息类型
- python判断数字_python判断变量是否为数字、字符串、列表、字典等
- python学习-类(类方法、实例方法、静态方法)