OData 集成(AspNetCore)

介绍

OData被定义为“允许以简单和标准的方式创建和使用可查询和可互操作的RESTful API的开放协议”(odata.org)。您可以将OData与ASP.NET Boilerplate一起使用。Abp.AspNetCore.OData  NuGet包简化了它的使用。

建立

安装NuGet包

我们必须首先将Abp.AspNetCore.OData NuGet包安装到我们的Web.Core项目中:

Install-Package Abp.AspNetCore.OData

设置模块依赖关系

我们需要为我们的模块设置对AbpAspNetCoreODataModule的依赖。例:

[DependsOn(typeof(AbpAspNetCoreODataModule))]
public class MyProjectWebCoreModule : AbpModule
{
    ...
}

请参阅  模块系统  以了解模块依赖性。

配置您的实体

OData要求我们声明可用作OData资源的实体。我们必须在Startup类中执行此操作:

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddOData();

        // Workaround: https://github.com/OData/WebApi/issues/1177
        services.AddMvcCore(options =>
        {
            foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
            {
                outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
            }
            foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
            {
                inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
            }
        });

        return services.AddAbp<MyProjectWebHostModule>(...);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAbp();

        ...

        app.UseOData(builder =>
        {
            builder.EntitySet<Person>("Persons").EntityType.Expand().Filter().OrderBy().Page();
        });

        // Return IQueryable from controllers
        app.UseUnitOfWork(options =>
        {
            options.Filter = httpContext =>
            {
                return httpContext.Request.Path.Value.StartsWith("/odata");
            };
        });

        app.UseMvc(routes =>
        {
            routes.MapODataServiceRoute(app);

            ...
        });
    }
}

在这里,我们获得了ODataModelBuilder引用并设置了Person实体。您可以使用EntitySet以类似的方式添加其他实体。请参阅  创建控制器

Abp.AspNetCore.OData NuGet包中包含AbpODataEntityController基类(扩展标准ODataController),以便更轻松地创建控制器。为Person实体创建OData端点的示例:

public class PersonsController : AbpODataEntityController<Person>, ITransientDependency 
{
    public PersonsController(IRepository<Person> repository)
        : base(repository)
    {
    }
}

就这么简单!AbpODataEntityController的所有方法都是虚拟的。这意味着您可以覆盖Get,Post,Put,Patch,Delete等操作并添加自己的逻辑。

组态

Abp.AspNetCore.OData使用传统配置调用IRouteBuilder.MapODataServiceRoute方法。如果需要,可以设置Configuration.Modules.AbpAspNetCoreOData()。MapAction来自己映射OData路由。

例子

以下是对上面定义的控制器的一些请求。假设应用程序在  http:// localhost:21021上运行我们将展示一些基本的例子。由于OData是标准协议,因此您可以在Web上轻松找到更高级的示例。

获取实体列表

让所有人。

请求
GET http://localhost:21021/odata/Persons
响应
{
  "@odata.context":"http://localhost:21021/odata/$metadata#Persons","value":[
    {
      "Name":"Douglas Adams","IsDeleted":false,"DeleterUserId":null,"DeletionTime":null,"LastModificationTime":null,"LastModifierUserId":null,"CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":1
    },{
      "Name":"John Nash","IsDeleted":false,"DeleterUserId":null,"DeletionTime":null,"LastModificationTime":null,"LastModifierUserId":null,"CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":2
    }
  ]
}

获得单一实体

获得Id = 2的人。

请求
GET http://localhost:21021/odata/Persons(2)
响应
{
  "@odata.context":"http://localhost:21021/odata/$metadata#Persons/$entity","Name":"John Nash","IsDeleted":false,"DeleterUserId":null,"DeletionTime":null,"LastModificationTime":null,"LastModifierUserId":null,"CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":2
}

使用导航属性获取单个实体

让Id = 1的人包括他/她的电话号码。

请求
GET http://localhost:21021/odata/Persons(1)?$expand=Phones
响应
{
  "@odata.context":"http://localhost:21021/odata/$metadata#Persons/$entity","Name":"Douglas Adams","IsDeleted":false,"DeleterUserId":null,"DeletionTime":null,"LastModificationTime":null,"LastModifierUserId":null,"CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":1,"Phones":[
    {
      "PersonId":1,"Type":"Mobile","Number":"4242424242","CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":1
    },{
      "PersonId":1,"Type":"Mobile","Number":"2424242424","CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":2
    }
  ]
}

查询

这是一个更高级的查询,包括过滤,排序和获得前2个结果。

请求
GET http://localhost:21021/odata/Persons?$filter=Name eq 'Douglas Adams'&$orderby=CreationTime&$top=2
响应
{
  "@odata.context":"http://localhost:21021/odata/$metadata#Persons","value":[
    {
      "Name":"Douglas Adams","IsDeleted":false,"DeleterUserId":null,"DeletionTime":null,"LastModificationTime":null,"LastModifierUserId":null,"CreationTime":"2015-11-07T20:12:39.363+03:00","CreatorUserId":null,"Id":1
    }
  ]
}

OData支持分页,排序,过滤,投影等等。有关 更多信息,请参阅  自己的文档

创建新实体

在这个例子中,我们正在创建一个新人。

请求
POST http://localhost:21021/odata/Persons

{
    Name: "Galileo Galilei"
}

这里,“Content-Type”标题是“application / json”。

响应
{
  "@odata.context": "http://localhost:21021/odata/$metadata#Persons/$entity",
  "Name": "Galileo Galilei",
  "IsDeleted": false,
  "DeleterUserId": null,
  "DeletionTime": null,
  "LastModificationTime": null,
  "LastModifierUserId": null,
  "CreationTime": "2016-01-12T20:36:04.1628263+02:00",
  "CreatorUserId": null,
  "Id": 4
}

如果我们再次获得列表,我们可以看到新人。我们还可以更新或删除现有实体,因为OData支持它。

获取MetaData

我们可以获取实体的元数据,如本例所示。

请求
GET http://localhost:21021/odata/$metadata
响应
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
    <edmx:DataServices>
        <Schema Namespace="AbpODataDemo.People" xmlns="http://docs.oasis-open.org/odata/ns/edm">

            <EntityType Name="Person">
                <Key>
                    <PropertyRef Name="Id" />
                </Key>
                <Property Name="Name" Type="Edm.String" Nullable="false" />
                <Property Name="IsDeleted" Type="Edm.Boolean" Nullable="false" />
                <Property Name="DeleterUserId" Type="Edm.Int64" />
                <Property Name="DeletionTime" Type="Edm.DateTimeOffset" />
                <Property Name="LastModificationTime" Type="Edm.DateTimeOffset" />
                <Property Name="LastModifierUserId" Type="Edm.Int64" />
                <Property Name="CreationTime" Type="Edm.DateTimeOffset" Nullable="false" />
                <Property Name="CreatorUserId" Type="Edm.Int64" />
                <Property Name="Id" Type="Edm.Int32" Nullable="false" />
                <NavigationProperty Name="Phones" Type="Collection(AbpODataDemo.People.Phone)" />
            </EntityType>

            <EntityType Name="Phone">
                <Key>
                    <PropertyRef Name="Id" />
                </Key>
                <Property Name="PersonId" Type="Edm.Int32" />
                <Property Name="Type" Type="AbpODataDemo.People.PhoneType" Nullable="false" />
                <Property Name="Number" Type="Edm.String" Nullable="false" />
                <Property Name="CreationTime" Type="Edm.DateTimeOffset" Nullable="false" />
                <Property Name="CreatorUserId" Type="Edm.Int64" />
                <Property Name="Id" Type="Edm.Int32" Nullable="false" />
                <NavigationProperty Name="Person" Type="AbpODataDemo.People.Person">
                    <ReferentialConstraint Property="PersonId" ReferencedProperty="Id" />
                </NavigationProperty>
            </EntityType>

            <EnumType Name="PhoneType">
                <Member Name="Unknown" Value="0" />
                <Member Name="Mobile" Value="1" />
                <Member Name="Home" Value="2" />
                <Member Name="Office" Value="3" />
            </EnumType>

        </Schema>
        <Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm">

            <EntityContainer Name="Container">
                <EntitySet Name="Persons" EntityType="AbpODataDemo.People.Person" />
            </EntityContainer>

        </Schema>
    </edmx:DataServices>
</edmx:Edmx>

元数据用于调查服务。

示例项目

您可以在此处获取示例项目的源代码:https:  //github.com/aspnetboilerplate/sample-odata

nidie.com.cn - 用心与你沟通