ResultToProblem 2.0.7

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

ResultToProblem

https://www.nuget.org/packages/ResultToProblem/

NuGet Version NuGet Downloads

ResultToProblem is a .NET library that extends the Result pattern and simplifies the conversion of domain results into standard HTTP responses using ProblemDetails.

Its purpose is to streamline error handling in ASP.NET Core applications, maintaining a clean and consistent style across endpoints and controllers.


Installation

Install the package from NuGet:

bash dotnet add package ResultToProblem


Basic Usage

Examples in an ASP.NET Core project

Minimal API endpoint using ResultToProblem:

Example 1:


program.cs:

using ResultToProblem.Domain.Common;
using ResultToProblem.Domain.Enums;
using ResultToProblem.Api.Extensions;

//....

app.MapGet("/", () =>
{
    var random = new Random();
    var temperature = random.Next(-10, 40);

    if (temperature < -5)
    {
        var result = Result.Failure(
            code: "WEATHER_SENSOR_FAILURE",
            message: "Temperature sensor error",            
            type: ErrorType.Unexpected
        );

        return Results.Problem(result.ToProblemDetails());
    }

    var success = Result.Success($"Today's temperature is {temperature}°C");
    return Results.Ok(success.Value);
});

app.Run();

Example 2:


program.cs:

using ResultToProblem.Domain.Common;
using ResultToProblem.Domain.Enums;
using ResultToProblem.Api.Extensions;

//....

app.MapGet("/", () =>
{
    var random = new Random();
    var temperature = random.Next(-10, 40);

    if (temperature < -5)
    {
        var result = Result.Failure(
            Error.Unexpected("WEATHER_SENSOR_FAILURE", "Temperature sensor error")
        );

        return Results.Problem(result.ToProblemDetails());
    }

    var success = Result.Success($"Today's temperature is {temperature}°C");
    return Results.Ok(success.Value);
});

app.Run();

Other combinations:


Error.Conflict("DUPLICATE_ENTRY", "User already exists")
Error.NotFound("USER_NOT_FOUND", "User record not found")
Error.Validation("INVALID_INPUT", "Temperature must be above zero")

ToValidationProblemDetails() extension for validation errors:


app.MapPost("/users", (UserDTO dto) =>
{
    var errors = new Dictionary<string, string[]>();

    if (string.IsNullOrWhiteSpace(dto.Email))
        errors.Add("Email", new[] { "Email cannot be empty" });
    else if (!Regex.IsMatch(dto.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
        errors.Add("Email", new[] { "Email format is invalid" });

    if (string.IsNullOrWhiteSpace(dto.Name))
        errors.Add("Name", new[] { "Name is required" });
    else if (dto.Name.Length < 3)
        errors.Add("Name", new[] { "Name must be at least 3 characters" });

    if (dto.Age < 18 || dto.Age > 120)
        errors.Add("Age", new[] { "Age must be between 18 and 120" });

    if (errors.Any())
    {
        var result = Result.Failure(
            message: "Validation failed",
            code: "USER_VALIDATION_ERROR",
            type: ErrorType.Validation,
            validationErrors: errors
        );

        return Results.ValidationProblem(result.ToValidationProblemDetails().Errors);
    }

    return Results.Ok(new { Message = "User created successfully" });
});

Using a centralized validator:


UserValidator.cs:

public static class UserValidator
{
    public static Result Validate(UserDTO dto)
    {
        var errors = new Dictionary<string, string[]>();

        if (string.IsNullOrWhiteSpace(dto.Email))
            errors.Add("Email", new[] { "Email cannot be empty" });
        else if (!Regex.IsMatch(dto.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
            errors.Add("Email", new[] { "Email format is invalid" });

        if (string.IsNullOrWhiteSpace(dto.Name))
            errors.Add("Name", new[] { "Name is required" });
        else if (dto.Name.Length < 3)
            errors.Add("Name", new[] { "Name must be at least 3 characters" });

        if (dto.Age < 18 || dto.Age > 120)
            errors.Add("Age", new[] { "Age must be between 18 and 120" });

        return errors.Any()
            ? Result.Failure("Validation failed", "USER_VALIDATION_ERROR", ErrorType.Validation, errors)
            : Result.Success(dto);
    }
}

program.cs:

app.MapPost("/users", (UserDTO dto) =>
{
    var result = UserValidator.Validate(dto);
    return result.IsSuccess
        ? Results.Ok(new { Message = "User created successfully" })
        : Results.ValidationProblem(result.ToValidationProblemDetails().Errors);
});

Using a centralized validator with a middleware:


ResultMiddleware.cs:

 public class ResultMiddleware
 {
     private readonly RequestDelegate _next;

     public ResultMiddleware(RequestDelegate next)
     {
         _next = next;
     }

    public async Task InvokeAsync(HttpContext context)
    {
        // Run the pipeline
        await _next(context);

        if (!context.Items.TryGetValue("Result", out var resultObj) || resultObj is not Result result)
            return;

        if (result.IsSuccess)
        {
            context.Response.StatusCode = StatusCodes.Status200OK;
            await context.Response.WriteAsJsonAsync(result.Value);
            return;
        }

        if (result.Error?.Type == ErrorType.Validation)
        {
            var validationProblem = result.ToValidationProblemDetails();
            context.Response.StatusCode = StatusCodes.Status400BadRequest;
            await context.Response.WriteAsJsonAsync(validationProblem);
            return;
        }

        var problem = result.ToProblemDetails();
        context.Response.StatusCode = problem.Status ?? StatusCodes.Status500InternalServerError;
        await context.Response.WriteAsJsonAsync(problem);
    }
 }

program.cs:

//Middleware Register
app.UseMiddleware<ResultMiddleware>();
 
app.MapPost("/users", (HttpContext ctx, UserDTO dto) =>
{
    var result = UserValidator.Validate(dto);

    // Store the result for middleware to process
    ctx.Items["Result"] = result;

    // Endpoint doesn’t return JSON directly — middleware handles it
    return Results.Empty;
});

Using FluentValidation library:


UserFluentValidator.cs:

using FluentValidation;

 public class UserFluentValidator : AbstractValidator<UserDTO>
 {
     public UserFluentValidator()
     {
         RuleFor(x => x.Email)
             .NotEmpty().WithMessage("Email cannot be empty")
             .EmailAddress().WithMessage("Email format is invalid");

         RuleFor(x => x.Name)
             .NotEmpty().WithMessage("Name is required")
             .MinimumLength(3).WithMessage("Name must be at least 3 characters");

         RuleFor(x => x.Age)
             .InclusiveBetween(18, 120).WithMessage("Age must be between 18 and 120");
     }
 }

program.cs:

using FluentValidation;
using FluentValidation.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

//...
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<UserFluentValidator>();

var app = builder.Build();

//...

app.MapPost("/users", async (UserDTO dto, IValidator<UserDTO> validator) =>
{
    var validationResult = await validator.ValidateAsync(dto);

    var result = validationResult.IsValid
        ? Result.Success(dto)
        : Result.Failure(Error.Validation(
            "ValidationError",
            "One or more validation errors occurred.",
            validationResult.Errors
                .GroupBy(e => e.PropertyName)
                .ToDictionary(
                    g => g.Key,
                    g => g.Select(e => e.ErrorMessage).ToArray()
                )
        ));

    if (result.IsSuccess)
    {
        return Results.Ok(new { Message = "User created successfully", User = dto });
    }

    return Results.ValidationProblem(result.ToValidationProblemDetails().Errors);
});

app.Run();

Using FluentValidation library with a middleware:


ResultMiddleware:

using ResultToProblem.Api.Extensions;
using ResultToProblem.Domain.Common;
using ResultToProblem.Domain.Enums;

public class ResultMiddleware
{
    private readonly RequestDelegate _next;

    public ResultMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Run the pipeline
        await _next(context);

        if (!context.Items.TryGetValue("Result", out var resultObj) || resultObj is not Result result)
            return;

        if (result.IsSuccess)
        {
            context.Response.StatusCode = StatusCodes.Status200OK;
            await context.Response.WriteAsJsonAsync(result.Value);
            return;
        }

        if (result.Error?.Type == ErrorType.Validation)
        {
            var validationProblem = result.ToValidationProblemDetails();
            context.Response.StatusCode = StatusCodes.Status400BadRequest;
            await context.Response.WriteAsJsonAsync(validationProblem);
            return;
        }

        var problem = result.ToProblemDetails();
        context.Response.StatusCode = problem.Status ?? StatusCodes.Status500InternalServerError;
        await context.Response.WriteAsJsonAsync(problem);
    }
}

UserFluentValidator.cs:

using FluentValidation;

 public class UserFluentValidator : AbstractValidator<UserDTO>
 {
     public UserFluentValidator()
     {
         RuleFor(x => x.Email)
             .NotEmpty().WithMessage("Email cannot be empty")
             .EmailAddress().WithMessage("Email format is invalid");

         RuleFor(x => x.Name)
             .NotEmpty().WithMessage("Name is required")
             .MinimumLength(3).WithMessage("Name must be at least 3 characters");

         RuleFor(x => x.Age)
             .InclusiveBetween(18, 120).WithMessage("Age must be between 18 and 120");
     }
 }

program.cs:

using FluentValidation;
using FluentValidation.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

//...
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<UserFluentValidator>();

var app = builder.Build();

//...

app.MapPost("/users", async (UserDTO dto, IValidator<UserDTO> validator, HttpContext context) =>
{
    var validationResult = await validator.ValidateAsync(dto);

    if (!validationResult.IsValid)
    {
        var errors = validationResult.Errors
            .GroupBy(e => e.PropertyName)
            .ToDictionary(
                g => g.Key,
                g => g.Select(e => e.ErrorMessage).ToArray()
            );

        var result = Result.Failure(Error.Validation("ValidationError", "Validation failed", errors));
        context.Items["Result"] = result;
        return; 
    }

    var success = Result.Success(dto);
    context.Items["Result"] = success;
});

app.Run();


✨ Features

  • Automatically converts Result objects into ProblemDetails
  • Standardized handling for common errors: NotFound, Validation, Conflict, Unexpected
  • Easy-to-use extensions for minimal API endpoints
  • Compatible with Clean Architecture and Domain-Driven Design

Support the Project

If you find this library useful, consider supporting its development:

Buy Me a Coffee


⚖️ License

This project is freely available under the MIT license.
You may use it without restrictions, as long as you retain the reference to the original license.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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
2.0.7 148 6/14/2026
2.0.6 112 5/13/2026
2.0.5 105 5/13/2026
2.0.4 107 5/13/2026
2.0.3 107 5/13/2026
2.0.2 108 5/12/2026
2.0.1 107 5/12/2026
2.0.0 109 5/12/2026
1.0.9 117 5/12/2026
1.0.8 105 5/11/2026
1.0.7 116 5/11/2026
1.0.6 108 5/11/2026
1.0.5 103 5/11/2026
1.0.4 116 5/8/2026
1.0.3 122 5/8/2026
1.0.2 109 5/8/2026
1.0.1 108 5/8/2026
1.0.0 112 5/8/2026