【翻译】在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

相关文章
|
2月前
|
存储 开发框架 NoSQL
ASP.NET WEB——项目中Cookie与Session的用法
ASP.NET WEB——项目中Cookie与Session的用法
29 0
|
2月前
|
开发框架 前端开发 .NET
ASP.NET WEB——项目创建与文件上传操作
ASP.NET WEB——项目创建与文件上传操作
46 0
|
3月前
|
开发框架 前端开发 JavaScript
盘点72个ASP.NET Core源码Net爱好者不容错过
盘点72个ASP.NET Core源码Net爱好者不容错过
71 0
|
3月前
|
开发框架 .NET
ASP.NET Core NET7 增加session的方法
ASP.NET Core NET7 增加session的方法
37 0
|
3月前
|
开发框架 JavaScript .NET
ASP.NET Core的超级大BUG
ASP.NET Core的超级大BUG
41 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
38 0
|
1月前
|
开发框架 中间件 .NET
C# .NET面试系列七:ASP.NET Core
## 第一部分:ASP.NET Core #### 1. 如何在 controller 中注入 service? 在.NET中,在ASP.NET Core应用程序中的Controller中注入服务通常使用<u>依赖注入(Dependency Injection)</u>来实现。以下是一些步骤,说明如何在Controller中注入服务: 1、创建服务 首先,确保你已经在应用程序中注册了服务。这通常在Startup.cs文件的ConfigureServices方法中完成。例如: ```c# services.AddScoped<IMyService, MyService>(); //
60 0
|
2月前
|
SQL 开发框架 .NET
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
67 0
|
2月前
|
SQL 开发框架 前端开发
ASP.NET WEB项目中GridView与Repeater数据绑定控件的用法
ASP.NET WEB项目中GridView与Repeater数据绑定控件的用法
32 0
|
2月前
|
SQL 开发框架 .NET
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
32 0