在Mac下创建ASP.NET Core Web API
文件,在ConfigureServices方法添加如下代码:添加控制器
控制器是用于处理HTTP请求并创建HTTP响应的对象,这里通过运行yo aspnet:webapicontroller UserController命令生成UserController控制器。
namespace UserWebAPI.Controllers
{
")]
public> {
public IUserRepository UserItems { get; set; }
public UserController(IUserRepository userItems)
{
UserItems = userItems;
}
}
}
获取用户信息
public IEnumerable<UserItem> GetAll()
{
return UserItems.GetAll();
}
public IActionResult GetById(string>
{
var item = UserItems.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
上述两个方法实现了两个GET方法:
[*]GET /api/user
[*]GET /api/user/{id}
运行dotnet restore、dotnet run之后,应用程序将会在本机启动,并在http://localhost:5000上开启监听服务。
然后在Postman上测试你的API接口是否能正确运行。
在GetById方法中:
public IActionResult GetById(string>
其中"{id}"是UserItem的ID占位符,当GetById被调用时,URL中的“{id}”值会被分配给该方法的id参数。
Name = "GetTodo"创建了一个命名的路由,并允许你在HTTP响应中链接到该路由。
GetAll方法返回了一个IEnumerable,MVC会自动将对象序列化成JSON并将JSON写入到响应消息的正文中。该方法的响应状态码为200,假设没有发生任何未处理异常。
而GetById方法返回的是一个更为通用的IActionResult类型。该方法有两种不同的返回类型:
[*]如果没有项匹配指定的请求ID,该方法通过返回NotFound表示一个404错误。
[*]否则,该方法返回一个JSON响应正文和200响应码,通过返回ObjectResult来表示。
添加新用户
public IActionResult Create(UserItem item)
{
if (item == null)
{
return BadRequest();
}
UserItems.Add(item);
return CreatedAtRoute("GetUser", new {>
}
通过 attribute 标明这个一个HTTP POST方法, attribute 告诉MVC从HTTP 请求的正文中获取用户UserItem值。
CreatedAtRoute方法返回一个201响应状态码(实际上是CreatedAtRouteResult对象),201状态码是通过POST方法在服务器上成功创建了一个新的资源时的标准响应码。CreateAtRoute也在响应里面添加了一个Location头信息,这个头信息指定了最新创建的User URI。
/// <summary>
/// Creates a <see cref="CreatedAtRouteResult"/> object that produces a Created (201) response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtRouteResult"/> for the response.</returns>
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, object routeValues,
object value)
{
return new CreatedAtRouteResult(routeName, routeValues, value);
}
/// <summary>
/// Initializes a new instance of the <see cref="CreatedAtRouteResult"/>>
/// provided.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The value to format in the entity body.</param>
public CreatedAtRouteResult(string routeName, object routeValues, object value)
: base(value)
{
RouteName = routeName;
RouteValues = routeValues == null ? null : new RouteValueDictionary(routeValues);
StatusCode = StatusCodes.Status201Created;
}
通过查看CreatedAtRouteResult的构造函数可以看到StatusCode(从ObjectResult对象继承而来)被直接设置成了Status201Created枚举值。
201状态码是当你在用POST/PUT在服务器端成功创建了一个新的资源时,服务器就应当返回201 Created同时在响应头添加一个Location来指定刚刚创建好的资源的URI。
通过Postman来发送Create请求
刚服务器接收到请求,会在VS Code的控制台显示出相应的信息:
点击Headers tab可以看到Location的值显示刚刚创建好的资源的URI。
更新用户信息(HTTP PUT)
public IActionResult Update(string>
{
if (item == null || item.Key !=> {
return BadRequest();
}
var user=UserItems.Find(id);
if(user==null)
{
return NotFound();
}
UserItems.Update(item);
return new NoContentResult();
}
采用了HTTP PUT标记Update方法,并且响应状态码设置为204(No Content)。根据HTTP规范,PUT请求要求客户端发送整个被更新实体,而不是增量更新部分。如果要支持局部更新,则需要使用HTTP PATCH。
204(No Content)状态码表示服务器已经成功处理了你的请求,但不需要返回具体的数据。浏览器不用刷新页面,也不用重定向到新的页面,会保留发送了该请求的页面,不产生任何文档视图上的变化,只停留在当前页面。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾。对提交到服务器进行处理的数据,如果只需要返回是否成功的话,可考虑使用状态码204来作为返回信息,从而减少多余的数据传输。
NoContentResult类在构造函数中调用了父类的构造函数并把Status204NoContent传给了该类。
namespace Microsoft.AspNetCore.Mvc
{
public> {
public NoContentResult()
: base(StatusCodes.Status204NoContent)
{
}
}
}
更新用户信息(HTTP PATCH)
public IActionResult Update( UserItem item, string>
{
if (item == null)
{
return BadRequest();
}
var user = UserItems.Find(id);
if (user == null)
{
return NotFound();
}
item.Key = user.Key;
UserItems.Update(item);
return new NoContentResult();
}
删除用户
public IActionResult Delete(string>
{
var user = UserItems.Find(id);
if (user == null)
{
return NotFound();
}
UserItems.Remove(id);
return new NoContentResult();
}
这个响应状态码同样是204(No Content)。
个人博客
我的个人博客
posted @ 2016-11-09 12:49 CharlieChu 阅读(...) 评论(...)编辑 收藏
刷新评论刷新页面返回顶部
公告
Copyright ©2017 CharlieChu
页:
[1]