CSharpFunctionalExtensions.HttpResults 1.0.0

dotnet add package CSharpFunctionalExtensions.HttpResults --version 1.0.0
                    
NuGet\Install-Package CSharpFunctionalExtensions.HttpResults -Version 1.0.0
                    
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="CSharpFunctionalExtensions.HttpResults" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpFunctionalExtensions.HttpResults" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="CSharpFunctionalExtensions.HttpResults" />
                    
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 CSharpFunctionalExtensions.HttpResults --version 1.0.0
                    
#r "nuget: CSharpFunctionalExtensions.HttpResults, 1.0.0"
                    
#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.
#addin nuget:?package=CSharpFunctionalExtensions.HttpResults&version=1.0.0
                    
Install CSharpFunctionalExtensions.HttpResults as a Cake Addin
#tool nuget:?package=CSharpFunctionalExtensions.HttpResults&version=1.0.0
                    
Install CSharpFunctionalExtensions.HttpResults as a Cake Tool

CSharpFunctionalExtensions.HttpResults

dotnet nuget version nuget downloads GitHub license

Seamlessly map Results from CSharpFunctionalExtensions to HttpResults for cleaner, more fluent Web APIs

<details> <summary><b>Table of Contents</b></summary>

  1. Overview
  2. Installation
  3. Usage
    1. Available methods
    2. Default mapping
    3. Custom error mapping
  4. Analyzers
  5. Examples
  6. Development </details>

Overview

This library provides convenient extension methods to seamlessly map Results from CSharpFunctionalExtensions to HttpResults. With this, it streamlines your Web API resulting in cleaner, more fluent code.

Key Benefits

  • ⚙️ Zero Configuration: Get started immediately — the mapping works out of the box without any configuration.
  • 🛠️ Customizable Mappings: Tailor default mappings or define custom mappings for specific use cases.
  • 🔗 Fluent API: Maintain a smooth, railway-oriented flow by chaining HttpResult mappings at the end of your Result chain.
  • 🧱 Separation of Domain and HTTP Errors: Keeps domain errors distinct from HTTP errors, improving maintainability and clarity between business logic and web API concerns.
  • Minimal APIs & Controllers Support: Works with both Minimal APIs and traditional controllers in ASP.NET.
  • 📦 Full Support for ASP.NET Results: Supports all built-in HTTP response types in ASP.NET, including Ok, Created, NoContent, Accepted, FileStream, and more.
  • 🦺 Typed Results: Utilizes TypedResults for consistent, type-safe API responses.
  • 📑 OpenAPI Ready: Ensures accurate OpenAPI generation for clear and reliable API documentation.
  • 🛡️ RFC Compliance: Default mappings adhere to the RFC 9457 standard (ProblemDetails), ensuring your API errors are standardized and interoperable.
  • 🧑‍💻 Developer-Friendly: Includes built-in analyzers and source generators to speed up development and reduce errors.

Installation

Available on NuGet.

dotnet add package CSharpFunctionalExtensions.HttpResults

or

PM> Install-Package CSharpFunctionalExtensions.HttpResults

[!NOTE] This library references an older version of CSharpFunctionalExtensions for wider compatibility. It's recommended to additionally install the latest version of CSharpFunctionalExtensions in your project to get the latest features and fixes.

Usage

This library provides you extension methods to map the following Result types to HttpResults at the end of our result chain:

  • Result
  • Result<T>
  • Result<T,E>
  • UnitResult<E>

Example:

app.MapGet("/books", (BookService service) =>
    service.Get()       //Result<Book[]>
      .ToOkHttpResult() //Results<Ok<Book[]>, ProblemHttpResult>
);

Available methods

<details> <summary><b>Click here</b> to view all available methods.</summary>

| Method | Short Description | |---------------------------------------|------------------------------------------------------------------------------| | .ToStatusCodeHttpResult() | Returns StatusCodeHttpResult or ProblemHttpResult | | .ToStatusCodeHttpResult<T>() | Returns StatusCodeHttpResult or ProblemHttpResult | | .ToStatusCodeHttpResult<T,E>() | Returns StatusCodeHttpResult or custom error | | .ToStatusCodeHttpResult<E>() | Returns StatusCodeHttpResult or custom error | | .ToJsonHttpResult<T>() | Returns JsonHttpResult<T> or ProblemHttpResult | | .ToJsonHttpResult<T,E>() | Returns JsonHttpResult<T> or custom error | | .ToOkHttpResult<T>() | Returns Ok<T> or ProblemHttpResult | | .ToOkHttpResult<T,E>() | Returns Ok<T> or custom error | | .ToNoContentHttpResult() | Returns NoContent or ProblemHttpResult | | .ToNoContentHttpResult<T>() | Discards value of Result<T> and returns NoContent or ProblemHttpResult | | .ToNoContentHttpResult<T,E>() | Discards value of Result<T> and returns NoContent or custom error | | .ToNoContentHttpResult<E>() | Returns NoContent or custom error | | .ToCreatedHttpResult<T>() | Returns Created<T> or ProblemHttpResult | | .ToCreatedHttpResult<T,E>() | Returns Created<T> or custom error | | .ToCreatedAtRouteHttpResult<T>() | Returns CreatedAtRoute<T> or ProblemHttpResult | | .ToCreatedAtRouteHttpResult<T,E>() | Returns CreatedAtRoute<T> or custom error | | .ToAcceptedHttpResult<T>() | Returns Accepted<T> or ProblemHttpResult | | .ToAcceptedHttpResult<T,E>() | Returns Accepted<T> or custom error | | .ToAcceptedAtRouteHttpResult<T>() | Returns AcceptedAtRoute<T> or ProblemHttpResult | | .ToAcceptedAtRouteHttpResult<T,E>() | Returns AcceptedAtRoute<T> or custom error | | .ToFileHttpResult<byte[]>() | Returns FileContentHttpResult or ProblemHttpResult | | .ToFileHttpResult<byte[],E>() | Returns FileContentHttpResult or custom error | | .ToFileStreamHttpResult<Stream>() | Returns FileStreamHttpResult or ProblemHttpResult | | .ToFileStreamHttpResult<Stream,E>() | Returns FileStreamHttpResult or custom error | | .ToContentHttpResult<string>() | Returns ContentHttpResult or ProblemHttpResult | | .ToContentHttpResult<string,E>() | Returns ContentHttpResult or custom error | </details>

All methods are available in sync and async variants.

Default mapping

By default, Result and Result<T> failures are mapped to a ProblemHttpResult based on RFC9457.

  • The status property contains the status code of the HTTP response. Note: For almost every method you can override the default status codes for Success/Failure case.
  • The type property contains a URI to the corresponding RFC9110 entry based on the status code.
  • The title property contains a generic short messages based on the status code.
  • The detail property contains the error string of the Result.

This default mapping behaviour is configured inside the ProblemDetailsMappingProvider.

Override default mapping

You can override this behavior by providing your own dictionary that maps status codes to their corresponding title and type of the resulting ProblemDetails object.

<details> <summary><b>Click here</b> to see an example of changing the default mapping for German localization.</summary>

ProblemDetailsMappingProvider.DefaultMappings = new Dictionary<int, (string? Title, string? Type)>
{
  { 400, ("Ungültige Anfrage", "https://tools.ietf.org/html/rfc9110#section-15.5.1") },
  { 401, ("Nicht autorisiert", "https://tools.ietf.org/html/rfc9110#section-15.5.2") },
  { 403, ("Verboten", "https://tools.ietf.org/html/rfc9110#section-15.5.4") },
  { 404, ("Nicht gefunden", "https://tools.ietf.org/html/rfc9110#section-15.5.5") },
  { 405, ("Methode nicht erlaubt", "https://tools.ietf.org/html/rfc9110#section-15.5.6") },
  { 406, ("Nicht akzeptabel", "https://tools.ietf.org/html/rfc9110#section-15.5.7") },
  { 408, ("Zeitüberschreitung der Anfrage", "https://tools.ietf.org/html/rfc9110#section-15.5.9") },
  { 409, ("Konflikt", "https://tools.ietf.org/html/rfc9110#section-15.5.10") },
  { 412, ("Vorbedingung fehlgeschlagen", "https://tools.ietf.org/html/rfc9110#section-15.5.13") },
  { 415, ("Nicht unterstützter Medientyp", "https://tools.ietf.org/html/rfc9110#section-15.5.16") },
  { 422, ("Nicht verarbeitbare Entität", "https://tools.ietf.org/html/rfc4918#section-11.2") },
  { 426, ("Upgrade erforderlich", "https://tools.ietf.org/html/rfc9110#section-15.5.22") },
  { 500, ("Ein Fehler ist bei der Verarbeitung Ihrer Anfrage aufgetreten.", "https://tools.ietf.org/html/rfc9110#section-15.6.1") },
  { 502, ("Schlechtes Gateway", "https://tools.ietf.org/html/rfc9110#section-15.6.3") },
  { 503, ("Dienst nicht verfügbar", "https://tools.ietf.org/html/rfc9110#section-15.6.4") },
  { 504, ("Gateway-Zeitüberschreitung", "https://tools.ietf.org/html/rfc9110#section-15.6.5") },
};

Example from here

</details>

You don't have to provide the whole dictionary; you can also override or add mappings for specific status codes like this:

ProblemDetailsMappingProvider.AddOrUpdateMapping(420, "Enhance Your Calm", "https://http-status-code.de/420/");

It's recommended to override the mappings during startup e.g. in Program.cs.

Override mapping for single use case

If you need to override the mapping for a specific use case in a single location, you can provide an Action<ProblemDetails> to fully customize the ProblemDetails. This is particularly useful when you want to add extensions or tailor the ProblemDetails specifically for that use case.

...
.ToOkHttpResult(customizeProblemDetails: problemDetails =>
{
  problemDetails.Title = "Custom Title";
  problemDetails.Extensions.Add("custom", "value");
});

Custom error mapping

When using Result<T,E> or UnitResult<E>, this library uses a Source Generator to generate extension methods for your own custom error types.

  1. Create a custom error type
    public record UserNotFoundError(string UserId);
    
  2. Create a mapper that implements IResultErrorMapper which maps this custom error type to an HttpResult / Microsoft.AspNetCore.Http.IResult that you want to return in your Web API:
    public class UserNotFoundErrorMapper : IResultErrorMapper<UserNotFoundError, ProblemHttpResult>
    {
        public ProblemHttpResult Map(UserNotFoundError error)
        {
            var problemDetails = new ProblemDetails
            {
                Status = 404,
                Title = "User not found",
                Type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
                Detail = $"The user with ID {error.UserId} couldn't be found.
            };
    
            return TypedResults.Problem(problemDetails);  
        };
    }
    
  3. Use the auto generated extension method:
    app.MapGet("/users/{id}", (string id, UserRepository repo) =>
        repo.Find(id)       //Result<User,UserNotFoundError>
          .ToOkHttpResult() //Results<Ok<User>,ProblemHttpResult>
    );
    

[!IMPORTANT]
Make sure that each custom error type has exactly one corresponding IResultMapper implementation.

[!TIP] You can use the ProblemDetailsMappingProvider.FindMapping() method to find a suitable title and type for a status code based on RFC9110.

[!NOTE] If extension methods for custom errors are missing, rebuild the project to trigger Source Generation.

Analyzers

This library includes analyzers to help you use it correctly.

For example, they will notify you if you have multiple mappers for the same custom error type.

You can find a complete list of all analyzers here.

Examples

The CSharpFunctionalExtensions.HttpResults.Examples project contains various examples demonstrating how to use this library in different scenarios, including:

Check out the example project for hands-on implementation details!

Development

Contributions are welcome! Please keep the following rules in mind:

  • add documentation in the form of summary comments
  • add tests for your additions
  • add sync and async variants where possible
  • refer to existing code files and the folder structure when adding something

This project uses CSharpier for code formatting. You can format your code with dotnet csharpier ..

Add new extension methods

To add new methods follow these steps:

  1. Add methods for Result and Result<T> to CSharpFunctionalExtensions.HttpResults.ResultExtensions
  2. Add methods for Result<T,E> to CSharpFunctionalExtensions.HttpResults.Generators.ResultExtensions and add the class to ResultExtensionsClassBuilder
  3. Add methods for UnitResult<E> to CSharpFunctionalExtensions.HttpResults.Generators.UnitResultExtensions and add the class to UnitResultExtensionsClassBuilder
  4. Add tests for all new methods to CSharpFunctionalExtensions.HttpResults.Tests
  5. Add methods to README
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  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 is compatible.  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.  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. 
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.0.0 422 3/26/2025
0.9.5 422 3/26/2025
0.9.4 133 3/19/2025
0.9.3 125 3/19/2025
0.9.2 126 3/19/2025
0.9.1 155 3/12/2025
0.9.0 148 3/11/2025
0.8.0 124 2/11/2025
0.7.0 105 2/11/2025
0.6.0 98 2/8/2025
0.5.0 193 1/2/2025
0.4.0 102 1/2/2025
0.3.2 99 1/2/2025
0.3.1 93 1/2/2025
0.3.0 97 1/2/2025
0.2.0 2,007 7/18/2024
0.1.0 97 7/18/2024
0.0.5 103 7/12/2024
0.0.4 99 7/12/2024
0.0.3 94 7/12/2024
0.0.2 109 6/17/2024
0.0.1 101 6/14/2024