ASP.NET Hosting

ASP.NET 9 Web API Entity Framework Minimal API

Web API for.Net 9 minimal Entity Framework API Here, we’ll go over how to use an Authorized JWT (JSON Web Token) token in Swagger web view to establish an Entity Framework in the.NET Minimal Web API. There are numerous possibilities for database storage in.NET, including MS SQL, MYSQL, PostgreSQL, MONGODB, and others. I’ll save the API data here using an example MSSQL database. First, use Visual Studio 2022 to construct a simple API in.NET Core 9.0. To make the web API safe on both the sender and recipient ends, open the program.cs file and add the JWT token authorization as well.

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

ASP.NET Core 10.0 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.