在ASP.NET Web API 1中启用CRUD操作

本文详细介绍如何使用ASP.NET WebAPI进行HTTP服务的CRUD操作,包括创建、读取、更新和删除产品列表的方法,以及如何正确使用HTTP方法如GET、PUT、POST和DELETE。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载完成的项目

本教程介绍如何使用ASP.NET Web API支持HTTP服务中的CRUD操作。

Visual Studio 2012

Web API 1(也适用于Web API 2)

CRUD代表“创建,读取,更新和删除”,这是四个基本的数据库操作。许多HTTP服务还通过REST或类似REST的API为CRUD操作建模。

在本教程中,您将构建一个非常简单的Web API来管理产品列表。每个产品都包含名称,价格和类别(例如“玩具”或“硬件”)以及产品ID。

 

The products API will expose following methods.

Action

HTTP method

Relative URI

Get a list of all products

GET

/api/products

Get a product by ID

GET

/api/products/id

Get a product by category

GET

/api/products?category=category

Create a new product

POST

/api/products

Update a product

PUT

/api/products/id

Delete a product

DELETE

/api/products/id

Notice that some of the URIs include the product ID in path. For example, to get the product whose ID is 28, the client sends a GET request for http://hostname/api/products/28.

Resources

The products API defines URIs for two resource types:

Resource

URI

The list of all the products.

/api/products

An individual product.

/api/products/id

Methods

The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows:

  • GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
  • PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs. For this tutorial, the API will not support creation through PUT.
  • POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
  • DELETE deletes a resource at a specified URI.

Note: The PUT method replaces the entire product entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred. This tutorial does not implement PATCH.

 

产品API将公开以下方法。

行动

HTTP方法

相对URI

获取所有产品的列表

Get

/ API /产品

按ID获取产品

Get

/ api / products / id

按类别获取产品

Get

/ api / products?category = category

创建一个新产品

POST

/ API /产品

更新产品

PUT

/ api / products / id

删除产品

DELETE

/ api / products / id

请注意,某些URI包含路径中的产品ID。例如,要获取ID为28的产品,客户端会发送GET请求http://hostname/api/products/28。

资源

产品API定义了两种资源类型的URI:

资源

URI

所有产品的清单。

/ API /产品

个别产品。

/ api / products / id

方法

可以将四种主要的HTTP方法(GET,PUT,POST和DELETE)映射到CRUD操作,如下所示:

GET在指定的URI处检索资源的表示。GET应该对服务器没有副作用。

PUT更新指定URI的资源。如果服务器允许客户端指定新的URI,则PUT还可用于在指定的URI处创建新资源。对于本教程,API不支持通过PUT创建。

POST创建一个新资源。服务器为新对象分配URI,并将此URI作为响应消息的一部分返回。

DELETE删除指定URI的资源。

注意:PUT方法取代整个产品实体。也就是说,期望客户端发送更新产品的完整表示。如果要支持部分更新,则首选PATCH方法。本教程不实现PATCH。

创建一个新的Web API项目

在“ 新建ASP.NET MVC 4项目”对话框中,选择“ Web API”,然后单击“ 确定”。

添加模型

一个模型是代表你的应用程序中的数据的对象。在ASP.NET Web API中,您可以使用强类型CLR对象作为模型,它们将自动序列化为客户端的XML或JSON。

将以下属性添加到Product类中。

namespace ProductStore.Models

{

    public class Product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Category { get; set; }

        public decimal Price { get; set; }

    }

}

 

创建资源

接下来,将在ProductsController类中添加一个方法来创建新产品。见下方

Public Product PostProduct(Product  item){

Item=repository.Add(item);

Return item;

}

 

注意有关此方法的两件事:

1.方法名称以”Post …”开头。要创建新产品,客户端会发送HTTP POST请求。

2.该方法采用Product类型的参数。在Web API中,具有复杂类型的参数从请求主体反序列化。因此,我们希望客户端以XML或JSON格式发送产品对象的序列化表示。

这种实现方式可行,但不完整。理想情况下,希望HTTP响应包含以下内容:

1.响应代码默认情况下Web API框架将响应状态代码设置为200(OK). 但根据HTTP/1.1协议POST请求导致创建资源时,服务器应回复状态201(已创建)

2.位置:当服务器创建资源时,它应该在响应的Location头中包含新资源的URI.

ASP.NET WEB API使操作HTTP响应消息变得容易。以下是改进的实现:

Public  HttpResponseMessage  PostProduct(Product  item){
item=repository.Add(item);

Var response=Request.CreateResponse<Product>(HttpStatusCode.Created,item);

 

String uri=Url.Link(“DefaultApi”,new {id=item.Id });

response.Headers.Location=new Uri(uri);

return response;

}

注意:方法返回类型现在是HttpResponseMessage 通过返回HttpResponseMessage而不是Product,我们可以控制Http响应消息的详细信息,包括状态代码和Location头。

该 CreateResponse方法创建一个HTTPResponseMessage并自动写入产品对象的序列化表示进入body的应答消息。

注意此示例不验证Product,模型验证的信息,参阅ASP.NET Web API中的模型验证 

 

更新资源

使用Put更新产品非常简单:

Public void  PutProduct(int id,Product  product){

Product.Id=id;

If(!repository.Update(product)){

throw new HTTPResponseException(HttpStatusCode.NotFound);

}

}

 

方法名称以”Put …”开头,因此Web API 将其与PUT请求匹配。该方法采用两个参数,产品ID和更新的产品。ID参数从URI路径采取,并且所述产品参数从请求体反序列化。默认情况下,.NET WEB API框架从路径中获取简单的参数类型,并从请求主体中获取复杂类型。

 

删除资源

 Public void DeleteProduct(int id){

Product item=repository.Get(id);

If(item==null){

Throw new HttpResponseException(HttpStatusCode.NotFound);

}

Repository.Remove(id);

}

如果DELETE请求成功,返回状态200(OK),其中包含描述状态的实体主体;  状态202(已接受),如果删除仍未决定; 或状态204(无内容),没有实体主体。在这种情况下,该DeleteProduct方法具有void返回类型,因此ASP.NET Web API会自动将其转换为状态代码204(无内容)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值