Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Minimal API #1140

Open
wants to merge 3 commits into
base: release-8.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions AspNetCoreOData.sln
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ODataAlternateKeySample", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BenchmarkServer", "sample\BenchmarkServer\BenchmarkServer.csproj", "{8346AD1B-00E3-462D-B6B1-9AA3C2FB2850}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ODataMiniApi", "sample\ODataMiniApi\ODataMiniApi.csproj", "{986A48E0-FA19-49D0-B716-4E60740D243C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -75,6 +77,10 @@ Global
{8346AD1B-00E3-462D-B6B1-9AA3C2FB2850}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8346AD1B-00E3-462D-B6B1-9AA3C2FB2850}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8346AD1B-00E3-462D-B6B1-9AA3C2FB2850}.Release|Any CPU.Build.0 = Release|Any CPU
{986A48E0-FA19-49D0-B716-4E60740D243C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{986A48E0-FA19-49D0-B716-4E60740D243C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{986A48E0-FA19-49D0-B716-4E60740D243C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{986A48E0-FA19-49D0-B716-4E60740D243C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -90,6 +96,7 @@ Global
{647EFCFA-55A7-4F0A-AD40-4B6EB1BFCFFA} = {B1F86961-6958-4617-ACA4-C231F95AE099}
{7B153669-A42F-4511-8BDB-587B3B27B2F3} = {B1F86961-6958-4617-ACA4-C231F95AE099}
{8346AD1B-00E3-462D-B6B1-9AA3C2FB2850} = {B1F86961-6958-4617-ACA4-C231F95AE099}
{986A48E0-FA19-49D0-B716-4E60740D243C} = {B1F86961-6958-4617-ACA4-C231F95AE099}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {540C9752-AAC0-49EA-BA60-78490C90FF86}
Expand Down
125 changes: 125 additions & 0 deletions sample/ODataMiniApi/AppDb.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//-----------------------------------------------------------------------------
// <copyright file="AppDb.cs" company=".NET Foundation">
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// See License.txt in the project root for license information.
// </copyright>
//------------------------------------------------------------------------------

using Microsoft.EntityFrameworkCore;

namespace ODataMiniApi;

public class AppDb : DbContext
{
public AppDb(DbContextOptions<AppDb> options) : base(options) { }

public DbSet<School> Schools => Set<School>();

public DbSet<Student> Students => Set<Student>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<School>().HasKey(x => x.SchoolId);
modelBuilder.Entity<Student>().HasKey(x => x.StudentId);
modelBuilder.Entity<School>().OwnsOne(x => x.MailAddress);
}
}

static class AppDbExtension
{
public static void MakeSureDbCreated(this WebApplication app)
{
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<AppDb>();

if (context.Schools.Count() == 0)
{
#region Students
var students = new List<Student>
{
// Mercury school
new Student { SchoolId = 1, StudentId = 10, FirstName = "Spens", LastName = "Alex", FavoriteSport = "Soccer", Grade = 87, BirthDay = new DateOnly(2009, 11, 15) },
new Student { SchoolId = 1, StudentId = 11, FirstName = "Jasial", LastName = "Eaine", FavoriteSport = "Basketball", Grade = 45, BirthDay = new DateOnly(1989, 8, 3) },
new Student { SchoolId = 1, StudentId = 12, FirstName = "Niko", LastName = "Rorigo", FavoriteSport = "Soccer", Grade = 78, BirthDay = new DateOnly(2019, 5, 5) },
new Student { SchoolId = 1, StudentId = 13, FirstName = "Roy", LastName = "Rorigo", FavoriteSport = "Tennis", Grade = 67, BirthDay = new DateOnly(1975, 11, 4) },
new Student { SchoolId = 1, StudentId = 14, FirstName = "Zaral", LastName = "Clak", FavoriteSport = "Basketball", Grade = 54, BirthDay = new DateOnly(2008, 1, 4) },

// Venus school
new Student { SchoolId = 2, StudentId = 20, FirstName = "Hugh", LastName = "Briana", FavoriteSport = "Basketball", Grade = 78, BirthDay = new DateOnly(1959, 5, 6) },
new Student { SchoolId = 2, StudentId = 21, FirstName = "Reece", LastName = "Len", FavoriteSport = "Basketball", Grade = 45, BirthDay = new DateOnly(2004, 2, 5) },
new Student { SchoolId = 2, StudentId = 22, FirstName = "Javanny", LastName = "Jay", FavoriteSport = "Soccer", Grade = 87, BirthDay = new DateOnly(2003, 6, 5) },
new Student { SchoolId = 2, StudentId = 23, FirstName = "Ketty", LastName = "Oak", FavoriteSport = "Tennis", Grade = 99, BirthDay = new DateOnly(1998, 7, 25) },

// Earth School
new Student { SchoolId = 3, StudentId = 30, FirstName = "Mike", LastName = "Wat", FavoriteSport = "Tennis", Grade = 93, BirthDay = new DateOnly(1999, 5, 15) },
new Student { SchoolId = 3, StudentId = 31, FirstName = "Sam", LastName = "Joshi", FavoriteSport = "Soccer", Grade = 78, BirthDay = new DateOnly(2000, 6, 23) },
new Student { SchoolId = 3, StudentId = 32, FirstName = "Kerry", LastName = "Travade", FavoriteSport = "Basketball", Grade = 89, BirthDay = new DateOnly(2001, 2, 6) },
new Student { SchoolId = 3, StudentId = 33, FirstName = "Pett", LastName = "Jay", FavoriteSport = "Tennis", Grade = 63, BirthDay = new DateOnly(1998, 11, 7) },

// Mars School
new Student { SchoolId = 4, StudentId = 40, FirstName = "Mike", LastName = "Wat", FavoriteSport = "Soccer", Grade = 64, BirthDay = new DateOnly(2011, 11, 15) },
new Student { SchoolId = 4, StudentId = 41, FirstName = "Sam", LastName = "Joshi", FavoriteSport = "Basketball", Grade = 98, BirthDay = new DateOnly(2005, 6, 6) },
new Student { SchoolId = 4, StudentId = 42, FirstName = "Kerry", LastName = "Travade", FavoriteSport = "Soccer", Grade = 88, BirthDay = new DateOnly(2011, 5, 13) },

// Jupiter School
new Student { SchoolId = 5, StudentId = 50, FirstName = "David", LastName = "Padron", FavoriteSport = "Tennis", Grade = 77, BirthDay = new DateOnly(2015, 12, 3) },
new Student { SchoolId = 5, StudentId = 53, FirstName = "Jeh", LastName = "Brook", FavoriteSport = "Basketball", Grade = 69, BirthDay = new DateOnly(2014, 10, 15) },
new Student { SchoolId = 5, StudentId = 54, FirstName = "Steve", LastName = "Johnson", FavoriteSport = "Soccer", Grade = 100, BirthDay = new DateOnly(1995, 3, 2) },

// Saturn School
new Student { SchoolId = 6, StudentId = 60, FirstName = "John", LastName = "Haney", FavoriteSport = "Soccer", Grade = 99, BirthDay = new DateOnly(2008, 12, 1) },
new Student { SchoolId = 6, StudentId = 61, FirstName = "Morgan", LastName = "Frost", FavoriteSport = "Tennis", Grade = 17, BirthDay = new DateOnly(2009, 11, 4) },
new Student { SchoolId = 6, StudentId = 62, FirstName = "Jennifer", LastName = "Viles", FavoriteSport = "Basketball", Grade = 54, BirthDay = new DateOnly(1989, 3, 15) },

// Uranus School
new Student { SchoolId = 7, StudentId = 72, FirstName = "Matt", LastName = "Dally", FavoriteSport = "Basketball", Grade = 77, BirthDay = new DateOnly(2011, 11, 4) },
new Student { SchoolId = 7, StudentId = 73, FirstName = "Kevin", LastName = "Vax", FavoriteSport = "Basketball", Grade = 93, BirthDay = new DateOnly(2012, 5, 12) },
new Student { SchoolId = 7, StudentId = 76, FirstName = "John", LastName = "Clarey", FavoriteSport = "Soccer", Grade = 95, BirthDay = new DateOnly(2008, 8, 8) },

// Neptune School
new Student { SchoolId = 8, StudentId = 81, FirstName = "Adam", LastName = "Singh", FavoriteSport = "Tennis", Grade = 92, BirthDay = new DateOnly(2006, 6, 23) },
new Student { SchoolId = 8, StudentId = 82, FirstName = "Bob", LastName = "Joe", FavoriteSport = "Soccer", Grade = 88, BirthDay = new DateOnly(1978, 11, 15) },
new Student { SchoolId = 8, StudentId = 84, FirstName = "Martin", LastName = "Dalton", FavoriteSport = "Tennis", Grade = 77, BirthDay = new DateOnly(2017, 5, 14) },

// Pluto School
new Student { SchoolId = 9, StudentId = 91, FirstName = "Michael", LastName = "Wu", FavoriteSport = "Soccer", Grade = 97, BirthDay = new DateOnly(2022, 9, 22) },
new Student { SchoolId = 9, StudentId = 93, FirstName = "Rachel", LastName = "Wottle", FavoriteSport = "Soccer", Grade = 81, BirthDay = new DateOnly(2022, 10, 5) },
new Student { SchoolId = 9, StudentId = 97, FirstName = "Aakash", LastName = "Aarav", FavoriteSport = "Soccer", Grade = 98, BirthDay = new DateOnly(2003, 3, 15) }
};

foreach (var s in students)
{
context.Students.Add(s);
}
#endregion

#region Schools
var schools = new List<School>
{
new School { SchoolId = 1, SchoolName = "Mercury Middle School", MailAddress = new Address { ApartNum = 241, City = "Kirk", Street = "156TH AVE", ZipCode = "98051" } },
new School { SchoolId = 2, SchoolName = "Venus High School", MailAddress = new Address { ApartNum = 543, City = "AR", Street = "51TH AVE PL", ZipCode = "98043" } },
new School { SchoolId = 3, SchoolName = "Earth University", MailAddress = new Address { ApartNum = 101, City = "Belly", Street = "24TH ST", ZipCode = "98029" } },
new School { SchoolId = 4, SchoolName = "Mars Elementary School ", MailAddress = new Address { ApartNum = 123, City = "Issaca", Street = "Mars Rd", ZipCode = "98023" } },
new School { SchoolId = 5, SchoolName = "Jupiter College", MailAddress = new Address { ApartNum = 443, City = "Redmond", Street = "Sky Freeway", ZipCode = "78123" } },
new School { SchoolId = 6, SchoolName = "Saturn Middle School", MailAddress = new Address { ApartNum = 11, City = "Moon", Street = "187TH ST", ZipCode = "68133" } },
new School { SchoolId = 7, SchoolName = "Uranus High School", MailAddress = new Address { ApartNum = 123, City = "Greenland", Street = "Sun Street", ZipCode = "88155" } },
new School { SchoolId = 8, SchoolName = "Neptune Elementary School", MailAddress = new Address { ApartNum = 77, City = "BadCity", Street = "Moon way", ZipCode = "89155" } },
new School { SchoolId = 9, SchoolName = "Pluto University", MailAddress = new Address { ApartNum = 12004, City = "Sahamish", Street = "Universals ST", ZipCode = "10293" } }
};

foreach (var s in schools)
{
s.Students = students.Where(std => std.SchoolId == s.SchoolId).ToList();

context.Schools.Add(s);
}
#endregion

context.SaveChanges();
}
}
}
}
65 changes: 65 additions & 0 deletions sample/ODataMiniApi/AppModels.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//-----------------------------------------------------------------------------
// <copyright file="AppModels.cs" company=".NET Foundation">
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// See License.txt in the project root for license information.
// </copyright>
//------------------------------------------------------------------------------

using Microsoft.EntityFrameworkCore;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
using System.ComponentModel.DataAnnotations.Schema;

namespace ODataMiniApi;

public class EdmModelBuilder
{
public static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<School>("Schools");
builder.ComplexType<Address>();
builder.ComplexType<Student>();
return builder.GetEdmModel();
}
}

public class School
{
public int SchoolId { get; set; }

public string SchoolName { get; set; }

public Address MailAddress { get; set; }

public virtual IList<Student> Students { get; set; }
}

public class Student
{
public int StudentId { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string FavoriteSport { get; set; }

public int Grade { get; set; }

public int SchoolId { get; set; }

public DateOnly BirthDay { get; set; }
}

[ComplexType]
public class Address
{
public int ApartNum { get; set; }

public string City { get; set; }

public string Street { get; set; }

public string ZipCode { get; set; }
}
151 changes: 151 additions & 0 deletions sample/ODataMiniApi/MetadataHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
//-----------------------------------------------------------------------------
// <copyright file="MetadataHandler.cs" company=".NET Foundation">
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// See License.txt in the project root for license information.
// </copyright>
//------------------------------------------------------------------------------

using System.Text;
using System.Text.Json;
using System.Xml;
using Microsoft.AspNetCore.OData;
using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
using Microsoft.OData.Edm.Validation;
using System.Text.Encodings.Web;

namespace ODataMiniApi;

public class MetadataHandler
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this is in the sample project, does this mean this is something the customer will have to write, or does this work out of the box?

{
public static async Task HandleMetadata(HttpContext context)
{
IEdmModel model = GetEdmModel(context);
if (IsJson(context))
{
await WriteAsJson(context, model);
}
else
{
await WriteAsXml(context, model);
}
}

internal static async Task WriteAsJson(HttpContext context, IEdmModel model)
{
context.Response.ContentType = "application/json";

JsonWriterOptions options = new JsonWriterOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Indented = true,
SkipValidation = false
};

// we can't use response body directly since ODL writes the JSON CSDL using Synchronous operations.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we prioritize making this async in ODL?

using (MemoryStream memStream = new MemoryStream())
{
using (Utf8JsonWriter jsonWriter = new Utf8JsonWriter(memStream, options))
{
CsdlJsonWriterSettings settings = new CsdlJsonWriterSettings();
settings.IsIeee754Compatible = true;
IEnumerable<EdmError> errors;
bool ok = CsdlWriter.TryWriteCsdl(model, jsonWriter, settings, out errors);
jsonWriter.Flush();
}

memStream.Seek(0, SeekOrigin.Begin);
string output = new StreamReader(memStream).ReadToEnd();
await context.Response.WriteAsync(output).ConfigureAwait(false);
}
}

internal static async Task WriteAsXml(HttpContext context, IEdmModel model)
{
context.Response.ContentType = "application/xml";

// we can't use response body directly since ODL writes the XML CSDL using Synchronous operations.
//XmlWriterSettings settings = new XmlWriterSettings();
//settings.Encoding = Encoding.UTF8;
//settings.Indent = true; // for better readability

//using (XmlWriter xw = XmlWriter.Create(context.Response.Body, settings))
//{
// IEnumerable<EdmError> errors;
// CsdlWriter.TryWriteCsdl(model, xw, CsdlTarget.OData, out errors);
// xw.Flush();
//}

//await Task.CompletedTask;

using (StringWriter sw = new StringWriter())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true; // for better readability

using (XmlWriter xw = XmlWriter.Create(sw, settings))
{
IEnumerable<EdmError> errors;
CsdlWriter.TryWriteCsdl(model, xw, CsdlTarget.OData, out errors);
xw.Flush();
}

string output = sw.ToString();
await context.Response.WriteAsync(output).ConfigureAwait(false);
}
}

internal static bool IsJson(HttpContext context)
{
var acceptHeaders = context.Request.Headers.Accept;
if (acceptHeaders.Any(h => h.Contains("application/json", StringComparison.OrdinalIgnoreCase)))
{
// If Accept header set on Request, we use it.
return true;
}
else if (acceptHeaders.Any(h => h.Contains("application/xml", StringComparison.OrdinalIgnoreCase)))
{
return false;
}

StringValues formatValues;
bool dollarFormat = context.Request.Query.TryGetValue("$format", out formatValues) || context.Request.Query.TryGetValue("format", out formatValues);
if (dollarFormat)
{
if (formatValues.Any(h => h.Contains("application/json", StringComparison.OrdinalIgnoreCase)))
{
return true;
}
else if (formatValues.Any(h => h.Contains("application/xml", StringComparison.OrdinalIgnoreCase)))
{
return false;
}
}

return false;
}

private static IEdmModel GetEdmModel(HttpContext context)
{
// You can retrieve/create the Edm model by yourself, or create and use the Model Provider service
Endpoint endpoint = context.GetEndpoint();
ODataPrefixMetadata prefixMetadata = endpoint.Metadata.GetMetadata<ODataPrefixMetadata>();
if (prefixMetadata != null)
{
ODataOptions options = context.RequestServices.GetService<IOptions<ODataOptions>>()?.Value;
if (options != null)
{
if (options.RouteComponents.TryGetValue(prefixMetadata.Prefix, out var routeComponents))
{
return routeComponents.EdmModel;
}
}
}

throw new InvalidOperationException($"Please calling WithOData() to register the EdmModel.");
}
}
17 changes: 17 additions & 0 deletions sample/ODataMiniApi/ODataMiniApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.OData\Microsoft.AspNetCore.OData.csproj" />
</ItemGroup>

</Project>
Loading