KServerTools 1.1.3

dotnet add package KServerTools --version 1.1.3
                    
NuGet\Install-Package KServerTools -Version 1.1.3
                    
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="KServerTools" Version="1.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="KServerTools" Version="1.1.3" />
                    
Directory.Packages.props
<PackageReference Include="KServerTools" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add KServerTools --version 1.1.3
                    
#r "nuget: KServerTools, 1.1.3"
                    
#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.
#:package KServerTools@1.1.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=KServerTools&version=1.1.3
                    
Install as a Cake Addin
#tool nuget:?package=KServerTools&version=1.1.3
                    
Install as a Cake Tool

KServerTools

KServerTools is a .NET Core package that provides common functionality for Kestrel servers. This package aims to simplify the development and maintenance of Kestrel-based applications by offering a set of reusable tools and utilities.

Features

  • Request Logging: Easily log incoming requests and responses.
  • Error Handling: Centralized error handling and custom error responses.
  • Configuration Management: Simplified configuration setup and management.
  • Performance Monitoring: Tools for monitoring and improving server performance.

Installation

To install KServerTools nuget, run the following command in your project directory:

dotnet add package KServerTools

Example Code repo

GitHub Example Repository

Usage

Here's a basic example of how to use KServerTools in your Kestrel server:

// TODO
using KServerTools.Common;

var builder = WebApplication.CreateBuilder(args);
IServiceCollection services = builder.Services;
services.AddControllers();
services
    // KST Add-ons
    .KSTAddRequestContext<RequestContext>()
    .KSTAddCommon()
    .KSTAddLogger()
    .KSTAddSqlServiceConnectionString<UserDatabaseSqlServerConfiguration>()

    // Configs
    .AddSingleton(static impl=> {
        var configHelper = impl.GetService<ConfigurationHelper>() ?? throw new InvalidOperationException("ConfigurationHelper service is not available.");
        var config = configHelper.TryGet<UserDatabaseSqlServerConfiguration>() ?? throw new InvalidOperationException("UserDatabaseSqlServerConfiguration could not be retrieved.");
        return config;
    })

var app = builder.Build();
app.Run();

Example Config Update the {{USER_ID}} with a real user Id Update the {{PASSWORD_TO_BE_SET_HERE_EXAMPLE}} with your real password

  "UserDatabaseSqlServerConfiguration": {
    "ConnectionStringData": "Server=tcp:localhost,1433;Initial Catalog=UserDb;Persist Security Info=False;User ID={{USER_ID}};Password={{PASSWORD_TO_BE_SET_HERE_EXAMPLE}};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;",
    "Server": "localhost,1433",
    "Database": "UserDb",
    "Scopes": [
      "https://database.windows.net/.default"
    ]
  }

Service Principal Configuration / AKV Example

Example on how to use the injection and create the configuration objects. The DefaultServicePrincipalConfiguration inherits from ServicePrincipalConfiguration and allows you to load any number of SPs. You can just use ServicePrincipalConfiguration if you only have one.

When loading the SP via DI, you can specify the configuration name "ServicePrincipalConfiguration" in the line: .KSTAddServicePrincipalCredentialWithConfig<DefaultServicePrincipalConfiguration>(nameof(ServicePrincipalConfiguration))

Notice that the configuration uses akv://SpClientSecret. This means you need a secret resolver and an AKV.

// The configuration object where the details will be loaded into.
public class DefaultServicePrincipalConfiguration : ServicePrincipalConfiguration {
}

/// ...
var builder = WebApplication.CreateBuilder(args);
IServiceCollection services = builder.Services;
services
    .KSTAddSecretResolver()
    .KSTAddKeyVault<DefaultAzureKeyVaultConfiguration, IDefaultCredential>(nameof(AzureKeyVaultConfiguration)) // use the Default Credential
    .KSTAddServicePrincipalCredentialWithConfig<DefaultServicePrincipalConfiguration>(nameof(ServicePrincipalConfiguration))
    .KSTAddSqlService<UserDatabaseSqlServerConfiguration, IServicePrincipalCredential<DefaultServicePrincipalConfiguration>>()
    .AddSingleton<UserDatabaseSqlServerConfiguration>(static impl=> {
        var configHelper = impl.GetService<ConfigurationHelper>() ?? throw new InvalidOperationException("ConfigurationHelper service is not available.");
        // Read from the appsettings.json
        var config = configHelper.TryGet<UserDatabaseSqlServerConfiguration>() ?? throw new InvalidOperationException("UserDatabaseSqlServerConfiguration could not be retrieved.");
        config.SecretResolver = GetSecretResolver<DefaultAzureKeyVaultConfiguration>(impl);
        return config;
    })

    // ** In DI Code we need to register the AKV with the secret resolver //
private static ISecretResolver GetSecretResolver<AKVConfig>(this IServiceProvider serviceProvider) where AKVConfig: IAzureKeyVaultConfiguration {
    ISecretResolver secretResolver = serviceProvider.GetService<ISecretResolver>() ?? throw new InvalidOperationException("ISecretResolver service is not available.");
    IAzureKeyVaultService<AKVConfig> akvService = serviceProvider.GetService<IAzureKeyVaultService<AKVConfig> >() ?? throw new InvalidOperationException("ISecretResolver service is not available.");
    secretResolver.RegisterKeyVaultService(akvService);
    return secretResolver;
}

Example of a configuration to get the SP secrets. The configuration name can be configured.

  "AzureKeyVaultConfiguration": {
    "Uri": "https://{{AKV_NAME}}.vault.azure.net/",
    "CacheDurationInSeconds": 300
  },
  "ServicePrincipalConfiguration": {
    "TenantId": "tenant-id",
    "ApplicationId": "app-id",
    "SecretData": "akv://SpClientSecret"
  },

Azure Queue Example

    private static IServiceCollection AddServerTools(this IServiceCollection serviceCollection) =>
        serviceCollection
            .KSTAddCommon() // Adds the IDefaultCredential
            .KSTAddAzureStorageQueue<AzureStorageQueueConfig, IDefaultCredential>(nameof(AzureStorageQueueConfig));
  "AzureStorageQueueConfig" : {
    "AccountName": "dastr",
    "Endpoint": "queue.core.windows.net"
  }

Contributing

We welcome contributions! Please see our contributing guidelines for more information.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.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
1.1.3 181 2/25/2025
1.1.2 177 2/17/2025
1.1.1 165 2/13/2025
1.1.0 192 2/2/2025
1.0.4 170 1/19/2025
1.0.3 168 1/11/2025
1.0.1 159 1/11/2025
1.0.0 159 1/11/2025