DEV Community

Cover image for ASP .NET Core model as json
Karen Payne
Karen Payne

Posted on

ASP .NET Core model as json

Introduction

When a developer needs to view the instance of a model at runtime, an easy way is to display the details as JSON. Here, learn how to do this was formatted json.

Below shows the result of colorized JSON using the NuGet package Spectre.Console.Json with formatting of JSON in the Program.cs

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.WriteIndented = true;
});
Enter fullscreen mode Exit fullscreen mode

formated json returned using Microsoft EF Core

Class project SpectreConsoleJsonLibrary

Provides a method to render JSON colorized rather than placing the code in the front-end project, as this code is only needed for the development environment.

Sample

Inject using a primary constructor JsonOptions

public class ViewContactModel(
    Context context, 
    IOptions<JsonOptions> jsonOptions) : PageModel
{

. . .

Enter fullscreen mode Exit fullscreen mode

Add the following method to prevent runtime exceptions as per gets an object that indicates whether an object is ignored when a reference cycle is detected during serialization.

private JsonSerializerOptions JsonSerializerOptions() => new(jsonOptions.Value.SerializerOptions)
{
    ReferenceHandler = ReferenceHandler.IgnoreCycles
};
Enter fullscreen mode Exit fullscreen mode

Display the contact as JSON.

public Contact Contact { get; set; } = null!;

public async Task<IActionResult> OnGetAsync(int id)
{

    var contact = await ContactOperations.GetByIdentifier(context, id);

    if (contact is not null)
    {
        Contact = contact;

        var json = JsonSerializer.Serialize(Contact, JsonSerializerOptions());

        Utilities.DisplayJsonConsole(json, "Contact");
        return Page();
    }

    return NotFound();
}
Enter fullscreen mode Exit fullscreen mode

To ensure the JSON code above does not work outside of development, add IWebHostEnvironment env to the page constructor.

public class ViewContactModel(
    Context context, 
    IOptions<JsonOptions> jsonOptions, 
    IWebHostEnvironment env) : PageModel

. . .

Enter fullscreen mode Exit fullscreen mode

Next, modify OnGet to only display the JSON if in the development environment.

public async Task<IActionResult> OnGetAsync(int id)
{

    var contact = await ContactOperations.GetByIdentifier(context, id);

    if (contact is not null)
    {
        Contact = contact;

        if (env.IsDevelopment())
        {
            var json = JsonSerializer.Serialize(Contact, JsonSerializerOptions());

            Utilities.DisplayJsonConsole(json, "Contact");
        }

        return Page();
    }

    return NotFound();
}
Enter fullscreen mode Exit fullscreen mode

Source code

Front-end project JSON Methods EF Core project

Running provided sample

As provided the database is expected under (localdb)\\MSSQLLocalDB

To create the database and populate follow these instructions.

Top comments (0)