您的位置:首页 > 编程语言 > ASP

ASP.NET Core 1.0开发Web API程序

2016-06-17 16:59 573 查看

.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(实体类)

namespace TodoApi.Models
{
public class TodoItem
{
public string Key { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
}


ITodoRepository.cs(接口类)

using System.Collections.Generic;

namespace TodoApi.Models
{
public interface ITodoRepository
{
void Add(TodoItem item);
IEnumerable<TodoItem> GetAll();
TodoItem Find(string key);
TodoItem Remove(string key);
void Update(TodoItem item);
}
}


TodoRepository.cs(接口实现类,服务的具体实现)

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace TodoApi.Models
{
public class TodoRepository : ITodoRepository
{
static ConcurrentDictionary<string, TodoItem> _todoItems = new ConcurrentDictionary<string, TodoItem>();

public TodoRepository()
{
Add(new TodoItem() {Name = "Item1"});
}

public void Add(TodoItem item)
{
item.Key = Guid.NewGuid().ToString();
_todoItems[item.Key] = item;
}

public IEnumerable<TodoItem> GetAll()
{
return _todoItems.Values;
}

public TodoItem Find(string key)
{
TodoItem item;
_todoItems.TryGetValue(key, out item);
return item;
}

public TodoItem Remove(string key)
{
TodoItem item;
_todoItems.TryGetValue(key, out item);
_todoItems.TryRemove(key, out item);
return item;
}

public void Update(TodoItem item)
{
_todoItems[item.Key] = item;
}
}
}


步骤三、在Controllers文件夹中新增Controller类

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
 using TodoApi.Models;

namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
private ITodoRepository TodoItems { get; set; }

public TodoController(ITodoRepository todoRepository)
{
TodoItems = todoRepository;
}

[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
return TodoItems.GetAll();
}

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}

[HttpPost]
public IActionResult Create([FromBody] TodoItem todoItem)
{
if (null == todoItem)
{
return BadRequest();
}
TodoItems.Add(todoItem);
return CreatedAtRoute("GetTodo", new {controller = "todo", id = todoItem.Key}, todoItem);
}

public IActionResult Update(string id, [FromBody] TodoItem item)
{
if (item == null || item.Key != id)
{
return BadRequest();
}
var todo = TodoItems.Find(id);
if (todo == null)
{
return NotFound();
}
TodoItems.Update(item);
return new NoContentResult();
}

public void Delete(string id)
{
TodoItems.Remove(id);
}
}
}


ASP.NET Core 1.0带来的新特性这篇文章中有提到ASP.NET Core已经把MVC和Web API整合到一起了,所以我们看到Controller类引用的是Microsoft.AspNetCore.Mvc这个NuGet包了,从字面上也可以看出这个整合。

步骤四、编写用于启动应用的主入口程序

progrom.cs

using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace TodoApi
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()  // 使用Kestrel服务器
.UseContentRoot(Directory.GetCurrentDirectory())  // 指定Web服务器的对应的程序主目录
.UseStartup<Startup>()  // 指定Web服务器启动时执行的类型,这个约定是Startup类
.Build(); // 生成Web服务器
host.Run(); // 运行Web应用程序
}
}
}


步骤五、Startup类型实现

Startup.cs(这个是约定的启动应用时加载执行的类型,约定包括:类型的名称,自动生成的相关类方法)

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TodoApi.Models;

namespace TodoApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

// Add our respository type
services.AddSingleton<ITodoRepository, TodoRepository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMvc();
}
}
}


Startup构造函数里面主要是初始化配置,应用的配置可以是外部自定义的JSON文件,比如本例中的appsettings.json,我们甚至可以根据不同的环境(FAT,UAT,PRD等)生成给自环境使用的配置文件,比如:

appsettings.FAT.json、appsettings.UAT.json等,不同的环境根据环境变量{env.EnvironmentName}配置的值来读取相应的配置文件。这个{env.EnvironmentName}可以通过项目的Properties下的launchSettings.json文件进行配置,如下:

{
"TodoApi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "http://localhost:5000/api/todo",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "PRD"
}
}
}
}


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配置即可,如下:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Debug",
 "Microsoft": "Warning"
}
}
}


把“Microsoft”的值改成:“Warning”,这样上述info级别的日志就不会再输出了(Warning,Error级别的日志才会输出)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: