ASP.NET 5.0 的主要目标之一是统一MVC 和 Web API 框架应用。

接下来几篇文章中您会了解以下内容:
ASP.NET MVC 6 中创建简单的web API。
如何从空的项目模板中启动,及添加控件到应用中。
如何配置 ASP.NET 5.0 管道。
在 IIS 外对立部署应用。
本文的目的是从空的项目开始,逐步讲解如何创建应用。当然,您也可以从“Starter Web” 模板开始,它默认包含了MVC 6、权限、记录等其他模块,同时也内置了有效的控制器和视图在其中。
打开 Visual Studio 2015。点击File菜单,选择New>Project。
在New Project对话框中,点击Templates>Visual C#>Web,选择ASP.NET Web Application 项目模板。命名为 "TodoApi",点击 OK。

在New ASP.NET Project对话框中,选择 "ASP.NET 5.0 Empty" 模板。

下面的效果图展示了工程结构:

工程包含以下文件:
global.json 包含了解决方案级别的设置,允许工程到工程之间的引用。
project.json 包含了工程级别的设置。
Project_Readme.html 为 readme 文件。
Startup.cs 包含启动和配置代码。
Startup.cs 文件中的Startup类,配置了 ASP.NET 需求管道。当你使用空的项目模板,Startup类不会有任何实质性的代码加入到管道中:
public class Startup
{public void Configure(IApplicationBuilder app)
{// Nothing here!
}
}
现在,你可以运行应用了,但当前的应用没有任何功能。接下来我们会模拟"Starter Web" 项目模板来添加功能,例如 MVC 6、Entity Framework、身份验证、记录等功能。
打开 project.json 文件。该文件包含了工程设置内容。dependencies部分用于标注需要的NuGet 包和类库。添加 Microsoft.AspNet.Diagnostics 包到列表中:
"dependencies": {"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
// Add this:
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1"
},
输入时, Visual Studio 会提供智能提示:


接下来,打开 Startup.cs 文件,添加以下代码:
using System;
using Microsoft.AspNet.Builder;
namespace TodoApi
{public class Startup
{public void Configure(IApplicationBuilder app)
{// New code
app.UseWelcomePage();
}
}
}
点击 F5 运行,Visual Studio 启动浏览器,打开了 http://localhost:port/,端口号是一个Visual Studio随机分配的数字。运行效果如下:

欢迎界面是检验运行效果的快速入口,无需编写代码。
在本章节中,您将创建一个 ToDo 事项管理列表功能API。首先,我们需要添加 ASP.NET MVC 6 到应用中。
添加 MVC 6 到 project.json 文件的依赖列表中:
"dependencies": {"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
// New:
"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
接下来,添加 MVC 需求管道到 Startup.cs 文件中,
使用 using 声明Microsoft.Framework.DependencyInjection。
添加以下方法到Startup类中。
public void ConfigureServices(IServiceCollection services)
{services.AddMvc();
}
下面这段代码添加了 MVC 6 需要的所有依赖项,会自动在启动时调用ConfigureServices。
public void Configure(IApplicationBuilder app)
{// New:
app.UseMvc();
}
以下是完整的Startup类代码:
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
// New using:
using Microsoft.Framework.DependencyInjection;
namespace TodoApi
{public class Startup
{// Add this method:
public void ConfigureServices(IServiceCollection services)
{services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{// New:
app.UseMvc();
app.UseWelcomePage();
}
}
}
model代表应用的数据域。在本示例中,model 中存储 ToDo 项。 添加以下类到项目中:
using System.ComponentModel.DataAnnotations;
namespace TodoApi.Models
{public class TodoItem
{ public int Id { get; set; }[Required]
public string Title { get; set; } public bool IsDone { get; set; }}
}
为了保持项目的整洁,我创建了 Models 文件夹用于存放 Model 类,当然这不是必要的操作。
添加controller类用于处理 HTTP 请求。添加以下类到项目中:
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using System.Linq;
using TodoApi.Models;
namespace TodoApi.Controllers
{ [Route("api/[controller]")]public class TodoController : Controller
{static readonly List_items = new List ()
{ new TodoItem { Id = 1, Title = "First Item" }};
[HttpGet]
public IEnumerableGetAll()
{return _items;
}
[HttpGet("{id:int}", Name = "GetByIdRoute")]public IActionResult GetById (int id)
{var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null)
{return HttpNotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public void CreateTodoItem([FromBody] TodoItem item)
{if (!ModelState.IsValid)
{Context.Response.StatusCode = 400;
}
else
{item.Id = 1+ _items.Max(x => (int?)x.Id) ?? 0;
_items.Add(item);
string url = Url.RouteUrl("GetByIdRoute", new { id = item.Id },Request.Scheme, Request.Host.ToUriComponent());
Context.Response.StatusCode = 201;
Context.Response.Headers["Location"] = url;
}
}
[HttpDelete("{id}")]public IActionResult DeleteItem(int id)
{var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null)
{return HttpNotFound();
}
_items.Remove(item);
return new HttpStatusCodeResult(204); // 201 No Content
}
}
}
同样,我创建了 Controllers 文件夹用于存储 controller。
在后续的章节中我们将进一步阐述关于 Controller 的代码。以下是 controller 实现的一些基础功能:

例如,下面是获取 ToDo 项目的 HTTP 请求的:
GET http://localhost:5000/api/todo HTTP/1.1
User-Agent: Fiddler
Host: localhost:5000
下面是 response 流:
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 30 Oct 2014 22:40:31 GMT
Content-Length: 46
[{"Id":1,"Title":"First Item","IsDone":false}]后续章节中我们将阐述以下内容:
在配置方法中添加以下代码,UseMvc方法用于添加 MVC 6 到管道。
如何配置 ASP.NET 5.0 管道。
在 IIS 外对立部署应用。
原文链接:Create a Web API in MVC 6
ASP.NET 5系列教程 (一):领读新特性
ASP.NET 5系列教程 (二):Hello World
ASP.NET 5系列教程 (三):view components介绍
ASP.NET 5系列教程 (四):向视图中添加服务和发布应用到公有云
ASP.NET 5系列教程 (五):在Visual Studio 2015中使用Grunt、Bower开发Web程序
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。