Here we will discuss how to create an Entity Framework in .NET Minimal Web API with an Authorized JWT (JSON Web Token) token in Swagger web view. For database storage, so many options are available in .NET like MS SQL, MYSQL, PostgreSQL, MONGODB, Etc.
I will use an MSSQL Database example to save the API data here. First, create a minimal API in .NET Core 9.0 in Visual Studio 2022. Open program.cs file and add the JWT token authorization also, so that the web API gets secure at both the sender and receiver ends.
program.cs
builder.Services.AddSwaggerGen(options =>{
options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme {
Name = "Authorization",
Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Description = "my-key" );
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement { {
new Microsoft.OpenApi.Models.OpenApiSecurityScheme {
Reference = new Microsoft.OpenApi.Models.OpenApiReference {
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "Bearer" }},new string[] {} }}); });
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("my- key")) }; });builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthentication();
app.UseAuthorization();
This Entity Framework project mainly consists of Data, Model, Repositories folders, Program.cs Class and appsettings.json file.Here, Program.cs is going to act as the starting point and all the end points since we use a minimal API concept.
Project Structure
/BookApi
├── Data/
│ └── DbContextClass.cs│
├── Models/
│ └── Book.cs
├── Repositories/
│ └── BookRepositories.cs
│ └──IBookRepositories.cs
├── Program.cs
├── appsettings.json
Model.cs
public class Books
{
[Key]
public int Id { get; set; }
[Required]
public required string Name { get; set; }
[Required]
public required string Author { get; set; }
public DateOnly PublishDate { get; set; }
}
DbContextClass.cs
public class DbContextClass : DbContext
{
public DbContextClass(DbContextOptions<DbContextClass> options) : base(options)
{
}
public DbSet<Books> books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Books>()
.Property(b => b.PublishDate)
.HasConversion(
v => v.ToDateTime(TimeOnly.MinValue),
v => DateOnly.FromDateTime(v)
);
base.OnModelCreating(modelBuilder);
}
}
After creating the model class, we need to execute the following migration commands, so that the Table will be created in the DB automatically.
dotnet ef migrations add InitialCreate
dotnet ef database update
API Endpoint GET and POST code example given below, and the remaining code example added in zip folder
app.MapGet("/books", [Authorize] async (IBookRepositories repo) =>
{
var book= await repo.GetAllBooksAsync();
return Results.Ok( book);
});
app.MapGet("/bookID", [Authorize] async (IBookRepositories repo,int id) =>
{
var book = await repo.GetBookByIdAsync(id);
return Results.Ok(book);
});
app.MapPost("/books", [Authorize] async (IBookRepositories repo, Books book) =>
{
await repo.AddBookAsync(book);
return Results.Created($"/books/{book.Id}", book);
});
app.Run();
Output
![.Net 9 Web API Minimal API with Entity Framework]()