且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WebApi OData 4,用于在控制器中批量插入的第二个 POST 端点

更新时间:2023-02-12 22:47:24

OData 规范包括一个 批处理 概念,但对于这个问题 OData 操作 是一种更清洁的解决方案.该操作将绑定到 Teams 实体集,并将接受请求负载中的 Team 实体集合.(我已在下面的代码中将 USER_TEAMS 更改为 Team.)

The OData spec includes a batching concept, but for this problem an OData action is a cleaner solution. The action will be bound to the Teams entity set and will accept a collection of Team entities in the request payload. (I've changed USER_TEAMS to Team in the code below.)

给定以下Team实体类型的简单定义:

Given the following simple definition of Team entity type:

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
}

首先,在与 Post 方法相同的控制器中定义 action 方法.

First, define the action method in the same controller as your Post method.

    [HttpPost]
    public IHttpActionResult BulkAdd(ODataActionParameters parameters)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        var newTeams = (IEnumerable<Team>)parameters["NewTeams"];

        // Your data access layer logic goes here.

        return this.StatusCode(HttpStatusCode.NoContent);
    }

然后在您的 Web API 配置代码中声明 OData 操作.

Then declare the OData action in your Web API configuration code.

    var builder = new ODataConventionModelBuilder();

    builder.Namespace = "TeamService";
    builder.EntitySet<Team>("Teams");
    builder.EntityType<Team>().Collection
        .Action("BulkAdd")
        .CollectionParameter<Team>("NewTeams");

以上注意事项:

  • EntityTypeConfiguration.Collection 是将操作绑定到 Team 实体集所必需的(相对于单个 Team 实体)
  • ActionConfiguration.CollectionParameter 需要指定参数是一个集合(相对于标量)
  • EntityTypeConfiguration<T>.Collection is necessary to bind the action to the Team entity set (vs. a single Team entity)
  • ActionConfiguration.CollectionParameter<T> is necessary to specify that the parameter is a collection (vs. a scalar)

在客户端上,调用操作如下.

On the client, invoke the action as follows.

POST http://domain/Teams/TeamService.BulkAdd
Content-Type: application/json

{"NewTeams": [{"Name": "Demons"}, {"Name": "Angels"}]}