.NET Core 개발 로그 의 OData(Open Data Protocol)

약술 하 다
OData,즉 Open Data Protocol 은 마이크로소프트 가 2007 년 에 내 놓 은 오픈 프로 토 콜 로 간단 하고 표준적 인 방식 으로 조회 식 및 대화 형 RESTful API 를 만 들 고 사용 하기 위 한 것 이다.
라 이브 러 리
.NET Core 에서 OData 기능 을 사용 하려 면 Microsoft.AspNetCore.OData 패 키 지 를 추가 해 야 합 니 다.

dotnet add package Microsoft.AspNetCore.OData
준비 모형 류

public class Address
{
 public string City { get; set; }
 public string Street { get; set; }
}
public enum Category
{
 Book,
 Magazine,
 EBook
}
public class Press
{
 public int Id { get; set; }
 public string Name { get; set; }
 public string Email { get; set; }
 public Category Category { get; set; }
}
public class Book
{
 public int Id { get; set; }
 public string ISBN { get; set; }
 public string Title { get; set; }
 public string Author { get; set; }
 public decimal Price { get; set; }
 public Address Address { get; set; }
 public Press Press { get; set; }
}
Edm 모델 만 들 기
OData 는 EDM,즉 Entity Data Model 을 사용 하여 데이터 의 구 조 를 설명 합 니 다.Startup 파일 에 생 성 방법 을 추가 합 니 다.

private static IEdmModel GetEdmModel()
{
  var builder = new ODataConventionModelBuilder();
  builder.EntitySet<Book>("Books");
  builder.EntitySet<Press>("Presses");
  return builder.GetEdmModel();
}
OData 서비스 등록
Startup 파일 의 Configure Services 방법 에 OData 서 비 스 를 등록 합 니 다.

services.AddOData();
services.AddMvc(options =>
  {
    options.EnableEndpointRouting = false;
  }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
여기 서 주의해 야 할 것 은.NET Core 2.2 에 기본적으로 끝 점 이 있 기 때문에 OData 의 끝 점 을 사용 하려 면 기본 옵션 을 비활성화 해 야 합 니 다.
등록 OData 끝 점
마찬가지 로 Startup 파일 에서 Configure 방법 에서 원래 의 등록 경로 내용 을 OData 등록 의 끝 점 으로 바 꿉 니 다.

app.UseMvc(b =>
{
  b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
메타 데이터 보이 기
프로그램 실행 후 접근https://localhost:5001/odata/$metadata 주 소 는 사용 가능 한 모든 모델 의 메타 데 이 터 를 볼 수 있 습 니 다.

<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <edmx:DataServices>
    <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
      <EntityType Name="Book">
        <Key>
          <PropertyRef Name="Id"/>
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false"/>
        <Property Name="ISBN" Type="Edm.String"/>
        <Property Name="Title" Type="Edm.String"/>
        <Property Name="Author" Type="Edm.String"/>
        <Property Name="Price" Type="Edm.Decimal" Nullable="false"/>
        <Property Name="Address" Type="Default.Address"/>
        <NavigationProperty Name="Press" Type="Default.Press"/>
      </EntityType>
      <EntityType Name="Press">
        <Key>
          <PropertyRef Name="Id"/>
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false"/>
        <Property Name="Name" Type="Edm.String"/>
        <Property Name="Email" Type="Edm.String"/>
        <Property Name="Category" Type="Default.Category" Nullable="false"/>
      </EntityType>
      <ComplexType Name="Address">
        <Property Name="City" Type="Edm.String"/>
        <Property Name="Street" Type="Edm.String"/>
      </ComplexType>
      <EnumType Name="Category">
        <Member Name="Book" Value="0"/>
        <Member Name="Magazine" Value="1"/>
        <Member Name="EBook" Value="2"/>
      </EnumType>
      <EntityContainer Name="Container">
        <EntitySet Name="Books" EntityType="Default.Book">
          <NavigationPropertyBinding Path="Press" Target="Presses"/>
        </EntitySet>
        <EntitySet Name="Presses" EntityType="Default.Press"/>
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>
컨트롤 러 생 성
본 고의 실례 에서 데이터베이스 조작 을 고려 하지 않 기 때문에 하 드 코드 방식 으로 필요 한 모델 대상 을 구축한다.

public class BooksController : ODataController
{
  private static IList<Book> Books {get; set;}
  public BooksController()
  {
    Books = new List<Book>
    {
      new Book
      {
        Id = 1,
        ISBN = "111-0-321-56789-1",
        Title = "Calculus",
        Price = 66.6m,
        Address = new Address
        {
          City = "Shanghai",
          Street = "Beijin Xi Road"
        },
        Press = new Press
        {
          Id = 1,
          Name = "Shanghai Tongji",
          Category = Category.Book
        }
      },
      new Book
      {
        Id = 2,
        ISBN = "222-2-654-00000-2",
        Title = "Linear Algebra",
        Price = 53.2m,
        Address = new Address
        {
          City = "Shanghai",
          Street = "Beijin Dong Road"
        },
        Press = new Press
        {
          Id = 2,
          Name = "Shanghai Fudan",
          Category = Category.EBook
        }
      }      
    };  
  }

  [EnableQuery]
  public IActionResult Get()
  {
    return Ok(Books);
  }

  [EnableQuery]
  public IActionResult Get(int key)
  {
    return Ok(Books.FirstOrDefault(b => b.Id == key));
  }
}
EnableQuery 기능 은 고급 조회 가 필요 한 장면 에 추가 해 야 합 니 다.
조회 하 다.
Controller 가입 후 접근https://localhost:5001/odata/Books주소,모든 북 데 이 터 를 얻 을 수 있 습 니 다.

{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books",
  "value": [
    {
      "Id": 1,
      "ISBN": "111-0-321-56789-1",
      "Title": "Calculus",
      "Author": null,
      "Price": 66.6,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Xi Road"
      }
    },
    {
      "Id": 2,
      "ISBN": "222-2-654-00000-2",
      "Title": "Linear Algebra",
      "Author": null,
      "Price": 53.2,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Dong Road"
      }
    }
  ]
}
방문 하 다.https://localhost:5001/odata/Books(1)주 소 는 키 값 이 1 인 북 데 이 터 를 얻 을 수 있 습 니 다.

{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books/$entity",
  "Id": 1,
  "ISBN": "111-0-321-56789-1",
  "Title": "Calculus",
  "Author": null,
  "Price": 66.6,
  "Address": {
    "City": "Shanghai",
    "Street": "Beijin Xi Road"
  }
}
고급 검색
OData 조회 의 고급 기능 을 사용 하려 면 종료 점 을 등록 할 때 해당 설정 을 추가 할 수 있 습 니 다.

app.UseMvc(b =>
{
  b.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
  b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
인터넷 주 소 를 방문 할 때 필요 한 조회 내용 을 추가 합 니 다.
https://localhost:5001/odata/Books?$select=Id,Title

{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books(Id,Title)",
  "value": [
    {
      "Id": 1,
      "Title": "Calculus"
    },
    {
      "Id": 2,
      "Title": "Linear Algebra"
    }
  ]
}
특정 조건 에 따라 데이터 내용 을 걸 러 내 려 면 쉽다.
https://localhost:5001/odata/Books?$filter=Price%20le%2060

{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books",
  "value": [
    {
      "Id": 2,
      "ISBN": "222-2-654-00000-2",
      "Title": "Linear Algebra",
      "Author": null,
      "Price": 53.2,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Dong Road"
      }
    }
  ]
}
총결산
OData 의 진정한 매력 은 고급 조회 기능 에 대한 지원 에 있 기 때문에 RESTful API 를 만 들 때 OData 를 사용 하 는 것 을 고려 하면 불필요 한 코드 작업 을 많이 줄 일 수 있 을 것 이다.
자,이상 이 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.

좋은 웹페이지 즐겨찾기