ywu279 / 01-JsonFileProductService

Display JSON data on a ASP.NET Razor page by adding a Service

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

01-JsonFileProductService

Display JSON (JavaScript Object Notation) data on a ASP.NET Razor page by the following steps:

  • adding a data source products.json under wwwroot
  • adding a Model Product.cs to define the C# representative or shape of the product
  • adding a Service JsonFileProductService.cs (retrieve the Json file >> Deserialize it to turn it into an array of products)
  • publishing this JsonFileProductService in Program.cs to tell ASP.NET that there's a service available builder.Services.AddTransient<JsonFileProductService>();

API (Application Programming Interface)

ability to call another thing in a formalized way

  • Here we want to make a tiny simple web API that provides these products as a service to people: If people go to the ...URL.../products, it will return these products details in a JSON format.
app.MapGet("/products", (context) =>
{
    var products = app.Services.GetService<JsonFileProductService>().GetProducts();
    var json = JsonSerializer.Serialize<IEnumerable<Product>>(products);
    context.Response.ContentType = "application/json";
    return context.Response.WriteAsync(json); 
});

Acknowledgements

This project is basically an learning outcome of ASP.NET Core 101.

products.json and other code can be found here

About

Display JSON data on a ASP.NET Razor page by adding a Service


Languages

Language:C# 41.5%Language:HTML 29.0%Language:CSS 28.1%Language:JavaScript 1.5%