Halifax.Api 1.3.13

There is a newer version of this package available.
See the version list below for details.
dotnet add package Halifax.Api --version 1.3.13                
NuGet\Install-Package Halifax.Api -Version 1.3.13                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Halifax.Api" Version="1.3.13" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Halifax.Api --version 1.3.13                
#r "nuget: Halifax.Api, 1.3.13"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Halifax.Api as a Cake Addin
#addin nuget:?package=Halifax.Api&version=1.3.13

// Install Halifax.Api as a Cake Tool
#tool nuget:?package=Halifax.Api&version=1.3.13                
Package Name NuGet
Halifax.Api     NuGet
Halifax.Core     NuGet
Halifax.Domain     NuGet
Halifax.Http     NuGet

Halifax Service Foundation

Simplistic libraries for complex projects. Halifax libraries are designed to speed up API service development process by encapsulating common functionality required for all microservices, allowing developers to focus on the business logic instead of copy-pasting the boilerplate code from project to project. The libraries are focussed on the following aspects of any application:

  • ✅ Exception handling
  • ✅ JWT Authentication
  • ✅ API models
  • ✅ HTTP Communication
  • ✅ Swagger
  • ✅ Logging
  • ✅ CORS

Installation

Install the API library using nuget package with Package Manager Console:

Install-Package Halifax.Api

Or using .NET CLI:

dotnet add package Halifax.Api

Getting Started

Please explore Peggy's Cove to get started as quickly as possible. For more details on certain topics, read the documentation. Here is what's needed to add Halifax to your project. In your Program.cs:

using Halifax.Api;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHalifax();
var app = builder.Build();

app.UseHalifax();
app.Run("https://*:5000");

This enables routing with controllers and exception handling.

Models

It's very beneficial when all the API responses follow the same format. It makes it easier to consume by the clients. In order to achieve it, there is a model called ApiResponse. It's designed to return response data, empty data or error information in the same consistent format. Here are the main use cases:

// Return API response with your model
return ApiResponse.With(model);

// Return empty API response
return ApiResponse.Empty;

When API response is used for all APIs in the project the response will always be of a format:

{
    data: {...} // your model
    success: true/false,
    error: { // null if successful
        type: "ArgumentNullException",
        message: "Email is required",
        trace: "(126) ArgumentNullException was thrown ... (typical exception stack trace)"
    }
}

Exceptions

There are 3 main exception types that can be used out of the box:

  • HalifaxException - resulting in 403 bad request.
  • HalifaxNotFoundException - 404 when resource is not found.
  • HalifaxUnauthorizedException - 401 unauthorized.

These exceptions are handled by Halifax exception handling middleware. Typical use case can look like this:

var user = await context.Users.FirstOrDefaultAsync(u => u.UserId == id);
if (user == null)
{
    throw new HalifaxNotFoundException("User not found");
}

The resulting HTTP response will have a status code 404 and JSON (using ApiResponse models):

{
  "data": null,
  "success": false,
  "error": {
    "message": "User not found"
  }
}

For more advanced scenarios you can override DefaultExceptionHandler or implement and register your own IExceptionHandler.

App Configuration

Halifax libraries are designed to work in containers. The most common way of configuring containers is by using Environment Variables. Halifax offers a few ways of working with it. Let's say we have env variables:

# It can also be a .env file in the root of your project. 
# Halifax always looks for .env to load it into the process. 
AppSettings__ConnectionString=localhost
AppSettings__HttpTimeout=120

Create class or a record (Yes, we support immutable records!):

record AppSettings(string ConnectionString, int HttpTimeout);

When halifax is added, this is how settings are being registered:

services.AddHalifax(builder => builder
    .AddSettings<AppSettings>()
    .AddSettings<AppSettings2>());

These calls do 3 things. They read the environment variables, map them to the setting classes or records and register these instances as singletons so that they can be injected into app services and controllers.

If there is a place where you can't inject your settings, you can get them from the Env directly. This is a very cheap operation, that can be executed any number of times:

var settings = Env.GetSection<AppSettings>();

If you need to load env variables from the file outside of the Halifax.Api, this is how it can be done:

// Here is how to load variables from the console if
// Halifax.Core is used outside of the Halifax.Api
Env.Load(); // or
Env.Load("filename", swallowErrors: false);

Note: supported types are limited to primitives, DateTime, TimeSpan, Guid at the moment. Arrays aren't allowed either. If more types are required, please request it.

JWT Authentication

Enable authentication/authorization using the following code. When you AddHalifax dependencies to services on app startup, make this call:

services.AddHalifax(builder => builder
    .ConfigureAuthentication("Your_JWT_secret",
        validateAudience: false,
        validateIssuer: false,
        requireExpirationTime: false));

When this is enabled all your non-[AllowAnonymous] will require "Authentication: Bearer {token}" header. Halifax provides a way to create tokens easily:

var claims = new List<Claim> 
{
    new Claim("ClaimType", "ClaimData"),
    ...
};
var expiration = DateTime.UtcNow.AddDays(90);
var token = Jwt.Create("Your_JWT_secret", claims, expiration);

You can access request token data from HttpContext.User.Claims. To verify that claims are correct there is a helper ClaimsAuthorizeFilterAttribute to override, it can be used for methods and controllers:

internal class MyClaimsAuthorize : ClaimsAuthorizeFilterAttribute
{
    protected override bool IsAuthorized(ActionExecutingContext context, List<Claim> claims)
    {
        // check your claims, return true/false or throw exception.
        // extension methods that can help:
        claims
            .ClaimExpected("ClaimType", "ClaimValue")
            .ClaimIsEmail("ClaimType", out var email);
            // etc.
        
        return true; // success
    }
}

If you need to read a token from string, use Jwt.Read("Your_JWT_secret", token).

MIT License

Copyright (c) 2020 Andrei M

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.0.0 66 11/19/2024
3.2.3 113 9/10/2024
3.2.2 436 8/7/2024
3.2.1 406 5/10/2024
3.2.0 139 3/22/2024
3.1.1 228 3/11/2024
3.1.0 294 2/11/2024
3.0.2 248 1/24/2024
3.0.1 488 11/27/2023
3.0.0 195 11/17/2023
2.0.9 163 10/30/2023
2.0.8 332 9/14/2023
2.0.7 320 8/16/2023
2.0.6 300 7/9/2023
2.0.5 560 3/20/2023
2.0.4 261 3/20/2023
2.0.3 458 2/24/2023
2.0.2 563 1/2/2023
2.0.1 321 1/2/2023
2.0.0 324 12/21/2022
1.3.21 355 12/13/2022
1.3.20 328 12/5/2022
1.3.19 324 12/5/2022
1.3.18 340 12/3/2022
1.3.17 587 10/16/2022
1.3.16 484 9/21/2022
1.3.15 588 8/19/2022
1.3.14 583 7/19/2022
1.3.13 488 7/11/2022
1.3.12 541 6/22/2022
1.3.11 500 6/20/2022
1.3.10 473 6/14/2022
1.3.9 453 6/13/2022
1.3.8 480 6/13/2022
1.3.7 446 6/11/2022
1.3.6 463 6/11/2022
1.3.5 603 6/1/2022
1.3.4 468 6/1/2022
1.3.3 471 6/1/2022
1.3.2 523 5/20/2022
1.3.1 688 4/17/2022
1.3.0 494 4/8/2022
1.2.1 593 3/12/2022
1.2.0 666 2/2/2022
1.1.5 471 12/31/2021
1.1.4 352 12/28/2021
1.1.3 420 12/19/2021
1.1.2 335 12/15/2021
1.1.1 318 12/15/2021
1.1.0 336 12/15/2021
1.0.7 326 12/10/2021
1.0.6 314 12/10/2021
1.0.5 307 12/10/2021
1.0.4 309 12/10/2021
1.0.3 311 12/10/2021
1.0.2 334 12/10/2021
1.0.1 325 12/10/2021
1.0.0 356 12/7/2021
0.3.0 548 12/6/2021
0.2.4 304 12/3/2021
0.2.3 358 11/22/2021
0.2.2 429 11/11/2021
0.2.1 356 11/11/2021
0.2.0 330 11/9/2021
0.1.1 343 11/3/2021
0.1.0 399 10/20/2021
0.0.22 404 10/20/2021
0.0.21 352 10/18/2021
0.0.20 370 10/4/2021
0.0.19 419 10/4/2021
0.0.18 344 10/4/2021
0.0.17 377 9/20/2021
0.0.16 347 9/16/2021
0.0.15 365 9/16/2021
0.0.14 444 9/8/2021
0.0.13 399 8/27/2021
0.0.12 371 8/27/2021
0.0.11 365 8/27/2021
0.0.10 365 8/17/2021
0.0.9 369 8/17/2021
0.0.8 361 8/12/2021
0.0.7 351 8/12/2021
0.0.6 358 8/11/2021
0.0.5 345 8/11/2021
0.0.4 386 8/10/2021
0.0.3 369 8/9/2021
0.0.2 366 8/9/2021
0.0.1 370 8/9/2021

v1.3.x - Configuration improvements
v1.3.5 - Claim extensions added
v1.3.x - Package version updates and minor improvements
v1.x.x - Stable version
v0.x.x - Initial release