(精华)2020年9月20日 ASP.NET Core WebAPI数据协议OData的使用

基本使用

首先注册Odata协议
引入

Microsoft.AspNetCore.OData
public static class ModelBuilder
    {
        public static IEdmModel GetEdmModel()
        {
            var odataBuilder = new ODataConventionModelBuilder();
            odataBuilder.EntitySet<Person>("Person");

            return odataBuilder.GetEdmModel();
        }
    }
public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddOData();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.Select().Filter().OrderBy().Count().MaxTop(10);
                endpoints.MapODataRoute("odata", "odata",ModelBuilder.GetEdmModel());
            });
        }
    }

使用

[Route("api/[controller]")]
    [ApiController]
    public class PersonController : ODataController
    {
        public static IList<Person> Persons = new List<Person>
        {
            new Person {Id = 1, Name = "张三", Age = 18},
            new Person {Id = 2, Name = "李四", Age = 19},
            new Person {Id = 3, Name = "王五", Age = 20},
            new Person {Id = 4, Name = "赵六", Age = 21},
        };

        [HttpGet, EnableQuery]
        public ActionResult Get()
        {
            return Ok(Persons);
        }

        [HttpGet, EnableQuery]
        public IActionResult Get([FromODataUri]int key)
        {
            return Ok(Persons.FirstOrDefault(b => b.Id == key));
        }


        [HttpPost]
        public IActionResult Post(Person person)
        {
            Persons.Add(person);
            return Created(person);
        }

        [HttpPatch]
        public IActionResult Patch([FromODataUri] int key, Delta<Person> person)
        {
            var updatePerson = Persons.FirstOrDefault(p => p.Id == key);
            if (updatePerson == null) return NotFound();

            person.Patch(updatePerson);
            return Updated(updatePerson);
        }

        [HttpDelete]
        public IActionResult Delete([FromODataUri] int key)
        {
            var deletePerson = Persons.FirstOrDefault(p => p.Id == key);
            if (deletePerson == null) return NotFound();

            Persons.Remove(deletePerson);
            return StatusCode(204); 
        }
    }
  1. 运行程序后访问https://localhost:5001/odata/$metadata地址,可以看到所有可用模型的元数据。
//获取所有
GET http://localhost:63372/odata/Person 
//获取id查询
GET http://localhost:63372/odata/Person(1)
//select
GET http://localhost:63372/odata/Person/?$select=Name,age
//select混合使用
GET http://localhost:63372/odata/Person/?$select=Name&$count=true&$orderby=age desc&$top=2&$skip=1
//过滤,按属性值
GET http://localhost:63372/odata/Person/?$filter=name eq '李四'
//过滤,按表达式-还可以使用各种函数startswith(name,'李')
GET http://localhost:63372/odata/Person/?$filter=Id add 2 eq 4

OData客户端的使用

首先安装扩展
在这里插入图片描述
在这里插入图片描述
使用

public static void Run()
{
    const string serviceRoot = "http://localhost:5000/odata/";
    var context = new Container(new Uri(serviceRoot));

    var persons = context.Person.Execute();
    foreach (var person in persons)
    {
        Console.WriteLine($"{person.Id} {person.Name} {person.Age}");
    }

    Console.Read();
}
public static void Run()
{
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddODataClient();

    var serviceProvider = serviceCollection.BuildServiceProvider();

    var oDataClientFactory = serviceProvider.GetService<IODataClientFactory>();
    var client = oDataClientFactory.CreateClient<Container>(new Uri("http://localhost:5000/odata/"));
    
    var persons = client.Person.Execute();
    foreach (var person in persons)
    {
        Console.WriteLine($"{person.Id} {person.Name} {person.Age}");
    }

    Console.Read();
}
public static void Run()
{
    const string serviceRoot = "http://localhost:5000/odata/";
    var client = new Container(new Uri(serviceRoot));

    // var query = client.Person.Where(p => p.Age >= 20).OrderByDescending(p=>p.Age);
    // Console.WriteLine($"QueryUri:{query}");
    //
    // var result = query.ToList();
    // foreach (var person in result)
    // {
    //     Console.WriteLine($"{person.Id} {person.Name} {person.Age}");
    // }
    // {
    //     // var person = new Person{Id = 99, Name = "Rick", Age = 99};
    //     // client.AddToPerson(person);
    //     // client.SaveChanges();
    //
    //     var query = client.Person
    //         .AddQueryOption("$filter", "Age lt 18")
    //         .AddQueryOption("$skip", "2")
    //         .AddQueryOption("$orderby", "Age desc");
    //
    //     foreach (var person in query)
    //     {
    //         Console.WriteLine($"{person.Id} {person.Name} {person.Age}");
    //     }
    // }
    

    {
        var query = client.Person.OrderByDescending(p=>p.Age);
        Console.WriteLine($"QueryUri:{query}");
    
        var result = query.ToList();
        foreach (var person in result)
        {
            Console.WriteLine($"{person.Id} {person.Name} {person.Age}");
        }

    }

    {
        var person = new Person {Id = 1};
        client.AttachTo("Person", person);
        client.DeleteObject(person);
        client.SaveChanges();
    }

    {
        var person = client.Person.ByKey(3).GetValue();
        person.Name = "Rick";
        client.UpdateObject(person);
        client.SaveChanges();

        client.AddToPerson(person);
        client.SaveChanges();
    }
   
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页