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

举报
愚公搬代码 发表于 2021/10/18 23:45:51 2021/10/18
【摘要】 基本使用 首先注册Odata协议 引入 Microsoft.AspNetCore.OData 1 public static class ModelBuilder { pub...

基本使用

首先注册Odata协议
引入

Microsoft.AspNetCore.OData

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

            return odataBuilder.GetEdmModel();
        }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
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());
            });
        }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

使用

[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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  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

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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();
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
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();
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
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();
    }
   
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。

原文链接:codeboy.blog.csdn.net/article/details/108524572

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。