zoukankan      html  css  js  c++  java
  • 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级别的日志才会输出)。

  • 相关阅读:
    什么是知行动手实验室?
    SpringBoot Admin2.0 集成 Java 诊断神器 Arthas 实践
    一文读懂容器存储接口 CSI
    AI 事件驱动场景 Serverless 实践
    一不小心,它成为了 GitHub Alibaba Group 下 Star 最多的开源项目
    5G 和云原生时代的技术下半场,视频化是最大最新的确定性
    基于 RocketMQ Prometheus Exporter 打造定制化 DevOps 平台
    Knative 基于流量的灰度发布和自动弹性实践
    阿里的 RocketMQ 如何让双十一峰值之下 0 故障?
    阿里巴巴开源容器镜像加速技术
  • 原文地址:https://www.cnblogs.com/frankyou/p/5594557.html
Copyright © 2011-2022 走看看