Skip to content

olohmann/Lohmann.HALight

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lohmann.HALight

A simple HAL formatter for ASP.NET Core MVC.

Note: This is a port of my ASP.NET WebApi 2 implementation.

Installation

Install via NuGet:

install-package Lohmann.HALight

Usage

Note: There is a sample in the repo to help you getting started.

In your Startup.cs:

public class Startup
{
    private readonly ILoggerFactory _loggerFactory;

    public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        _loggerFactory = loggerFactory;
    }

    public void ConfigureServices(
        IServiceCollection services)
    {
        var logger = _loggerFactory.CreateLogger<HalInputFormatter>();
        services.AddMvc(options =>
        {                
            options.InputFormatters.Add(new HalInputFormatter(logger));
            options.OutputFormatters.Add(new HalOutputFormatter());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {            
        // ...

        app.UseMvc();
    }
}

In your resource model:

using Lohmann.HALight;

public class UserResource : Resource
{
    public int Id { get; set; }

    public string Name { get; set; }
}

In your controller:

public class UsersController : Controller
{
    private readonly UserRepository _repository;

    // ...
    
    // Route: "/Users/{id}"
    public IActionResult Get(int id)
    {
        var user = _repository.Get(id);

        if (user == null)
        {
            return NotFound();
        }

        var userResource = new UserResource
        {
            Id = user.Id,
            Name = user.Name,            
        };

        userResource.Relations.Add(
            Link.CreateSelfLink(
                Url.Link(
                    "DefaultApi", 
                    new { controller = "Users", id = userDetailResource.Id })
            )
        );

        return Ok(userDetailResource);
    }
}

Acknowledgements

There a couple of other HAL libraries for ASP .NET Web API around that inspired my take on this subject. A big thank you to:

About

A simple HAL formatter for ASP.NET Core MVC

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages