【翻译】在Visual Studio中使用Asp.Net Core MVC创建第一个Web Api应用(二)

简介: 运行应用 In Visual Studio, press CTRL+F5 to launch the app. Visual Studio launches a browser and navigates to http://localhost:port/api/values, where port is a randomly chosen port number.

运行应用

In Visual Studio, press CTRL+F5 to launch the app. Visual Studio launches a browser and navigates to http://localhost:port/api/values, where port is a randomly chosen port number. If you're using Chrome, Edge or Firefox, the data will be displayed. If you're using IE, IE will prompt to you open or save the values.json file. Navigate to the Todocontroller we just created http://localhost:port/api/todo.

在Visual Studio中,按CTRL+F5运行程序。Visual Studio将运行默认浏览器并导航至http://localhost:port/api/values, 这个port端口是自动生成。如果你使用的是Chrome,Edge或者Firefox,将直接显示数据。如果你使用IE,IE会提示你打开或保存valuse.json文件。我们输入http://localhost:port/api/todo 将导航到TodoController。

执行其他的CRUD操作

We'll add Create, Update, and Delete methods to the controller. These are variations on a theme, so I'll just show the code and highlight the main differences. Build the project after adding or changing code.

我们将在Controller中添加Create、Update和Delete方法。模板中已经创建这些方法,我将会高亮我添加的代码。添加或者更改代码后生成项目。

[HttpPost]
public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }
    TodoItems.Add(item);
    return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
}
This is an HTTP POST method, indicated by the [HttpPost] attribute. The [FromBody] attribute tells MVC to get the value of the to-do item from the body of the HTTP request.

这使一个HTTP POST方法,使用了HTTPPost特性。FromBody特性告诉了MVC我们从HTTP request中获取to-do项所需要的值。

The CreatedAtRoute method returns a 201 response, which is the standard response for an HTTP POST method that creates a new resource on the server. CreateAtRoute also adds a Location header to the response. The Location header specifies the URI of the newly created to-do item. See 10.2.2 201 Created.

这个CreatedAtRoute方法返回一个201响应,它是当HTTP POST在服务器上创建新资源后的标准响应。CreateAtRoute方法在响应中添加了定位头信息,这个定位头信息提供了这个新对象的URI。详见:10.2.2 201 Created

使用Postman发送一个创建的请求

img_5ce8d676d8cc81b7653ec5ee4388f503.png

 

  • Set the HTTP method to POST

  • 设置HTTP方法为POST

  • Tap the Body radio button

  • 点击Body按钮

  • Tap the raw radio button

  • 选中raw选项

  • Set the type to JSON

  • 设置类型为JSON

  • In the key-value editor, enter a Todo item such as {"Name":"<your to-do item>"}

  • 在key-value编辑器中,输入一个Todo项,比如{"Name":"<your to-do item>"}

  • Tap Send

  • 点击Send

Tap the Headers tab and copy the Location header:

点击Headers选项卡,复制Location信息:

img_c89a085ad3f09455f80971a8fe388b81.png

You can use the Location header URI to access the resource you just created. Recall the GetById method created the "GetTodo" named route:

你可以使用这个定位头信息中的URI访问你刚创建的资源。还记得我们在GetById中创建的"GetTodo"路由:

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)

更新

[HttpPut("{id}")]
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();
}

Update is similar to Create, but uses HTTP PUT. The response is 204 (No Content). According to the HTTP spec, a PUT request requires the client to send the entire updated entity, not just the deltas. To support partial updates, use HTTP PATCH.

Update类似于Create,但使用的HTTP Put,响应代码204(无内容)。根据HTTP规范,PUT请求需要客户端发送整个更新实体,而不是部分。如果需要支持部分更新,需要使用HTTP PATCH。

img_63316188a24fe149327c9974b0549294.png

删除

[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
    var todo = TodoItems.Find(id);
    if (todo == null)
    {
        return NotFound();
    }

    TodoItems.Remove(id);
    return new NoContentResult();
}

The response is 204 (No Content).

相应代码为:204.

img_dc4768ff0e0933212ee83d72b19aba5d.png

原文链接

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api

相关文章
|
15天前
|
开发框架 监控 .NET
Visual Basic的Web服务和REST API开发指南
【4月更文挑战第27天】本文探讨了使用Visual Basic(VB.NET)构建Web服务和RESTful API的方法。首先介绍了Web服务的基础和REST API的概念,然后阐述了.NET Framework与.NET Core/.NET 5+对VB.NET的支持,以及ASP.NET Core在Web开发中的作用。接着,详细讲解了创建RESTful API的步骤,包括控制器与路由设置、模型绑定与验证,以及返回响应。此外,还讨论了安全措施、测试方法、部署选项和监控策略。最后强调,VB.NET开发者可以通过ASP.NET Core涉足现代Web服务开发,拓宽技术领域。
|
1月前
|
消息中间件 前端开发 小程序
一个基于.NET Core构建的简单、跨平台、模块化的商城系统
今天大姚给大家分享一个基于.NET Core构建的简单、跨平台、模块化、完全开源免费(MIT License)的商城系统:Module Shop。
|
1月前
|
算法 C# 数据库
【干货】一份10万字免费的C#/.NET/.NET Core面试宝典
C#/.NET/.NET Core相关技术常见面试题汇总,不仅仅为了面试而学习,更多的是查漏补缺、扩充知识面和大家共同学习进步。该知识库主要由自己平时学习实践总结、网上优秀文章资料收集(这一部分会标注来源)和社区小伙伴提供三部分组成。该份基础面试宝典完全免费,发布两年来收获了广大.NET小伙伴的好评,我会持续更新和改进,欢迎关注我的公众号【追逐时光者】第一时间获取最新更新的面试题内容。
|
12天前
|
弹性计算 JSON Shell
基于Web API的自动化信息收集和整理
【4月更文挑战第30天】
20 0
|
15天前
|
开发框架 缓存 前端开发
利用Visual Basic构建高效的ASP.NET Web应用
【4月更文挑战第27天】本文探讨使用Visual Basic与ASP.NET创建高效Web应用的策略,包括了解两者基础、项目规划、MVC架构、数据访问与缓存、代码优化、异步编程、安全性、测试及部署维护。通过这些步骤,开发者能构建出快速、可靠且安全的Web应用,适应不断进步的技术环境。
|
17小时前
|
设计模式 存储 前端开发
MVC(模型-视图-控制器)是一种在Web应用程序开发中广泛使用的软件设计模式
【5月更文挑战第12天】MVC模式是Web应用开发中的常见设计模式,将逻辑、数据和界面分离,提升代码可维护性和重用性。模型处理数据逻辑,视图展示数据,控制器协调用户输入与模型视图交互。优点包括代码分离、易维护、可扩展和组件重用,促进高效灵活的开发。
5 2
|
3天前
|
XML 开发框架 .NET
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
|
6天前
|
开发框架 JSON .NET
.Net4.0 Web.config 配置实践
.Net4.0 Web.config 配置实践
|
10天前
|
设计模式 前端开发 Java
19:Web开发模式与MVC设计模式-Java Web
19:Web开发模式与MVC设计模式-Java Web
20 4
|
14天前
|
JSON 安全 API
【专栏】四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥
【4月更文挑战第28天】本文探讨了四种REST API身份验证方法:基本认证、OAuth、JSON Web Token(JWT)和API密钥。基本认证简单但不安全;OAuth适用于授权第三方应用;JWT提供安全的身份验证信息传递;API密钥适合内部使用。选择方法时需平衡安全性、用户体验和开发复杂性。