using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ODataWithDotNet5Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ODataWithDotNet5Demo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpGet]
[EnableQuery]
public ActionResult<List<Student>> GetAllStudents()
{
return Ok(new List<Student>
{
new Student
{
Id = Guid.NewGuid(),
Name = "Viral Bahen",
Grade = 100
},
new Student
{
Id = Guid.NewGuid(),
Name = "Josh McCall",
Grade = 150
},
new Student
{
Id = Guid.NewGuid(),
Name = "Kailu Hu",
Grade = 90
}
});
}
}
}
Student 모델
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ODataWithDotNet5Demo.Models
{
public class Student
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
}
}
Startup.cs
// ** 추가된 부분 이라고 명시한 코드가 추가 또는 변경된 부분입니다.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.OData.Extensions;
namespace ODataWithDotNet5Demo
{
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().AddNewtonsoftJson(); // ** 변경추가된 부분
services.AddOData(); // ** 추가된 부분
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ODataWithDotNet5Demo", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ODataWithDotNet5Demo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.EnableDependencyInjection(); // ** 추가된 부분
endpoints.Select().Filter().Expand(); // ** 추가된 부분
endpoints.MapControllers();
});
}
}
}
실행한 결과
전체 조회
이름 필드값들만 반환받기
grade 필드 값 중에 110 보다 작은 데이터 가져오기
name 필드 값 중에 Viral Bahen 인 데이터 가져오기
문자열이므로 $filter=필드명 eq 'Viral Bahen' 처럼 홀따옴표 기재해 주어야 함