文件,在ConfigureServices方法添加如下代码:
添加控制器
控制器是用于处理HTTP请求并创建HTTP响应的对象,这里通过运行yo aspnet:webapicontroller UserController命令生成UserController控制器。
namespace UserWebAPI.Controllers
{
[Route("api/[controller]")]
public> {
public IUserRepository UserItems { get; set; }
public UserController(IUserRepository userItems)
{
UserItems = userItems;
}
}
}
获取用户信息
[HttpGet]
public IEnumerable<UserItem> GetAll()
{
return UserItems.GetAll();
}
[HttpGet("{id}", Name = "GetUser")]
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方法中:
[HttpGet("{id}", Name = "GetTodo")]
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来表示。
添加新用户
[HttpPost]
public IActionResult Create([FromBody]UserItem item)
{
if (item == null)
{
return BadRequest();
}
UserItems.Add(item);
return CreatedAtRoute("GetUser", new {>
}
通过[HttpPost] attribute 标明这个一个HTTP POST方法,[FromBody] 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>
[NonAction]
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)
[HttpPut("{id}")]
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)
[HttpPatch("{id}")]
public IActionResult Update([FromBody] 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();
}
删除用户
[HttpDelete("{id}")]
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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com