ResultFlow.AspNetCore
2.2.0
dotnet add package ResultFlow.AspNetCore --version 2.2.0
NuGet\Install-Package ResultFlow.AspNetCore -Version 2.2.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="ResultFlow.AspNetCore" Version="2.2.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ResultFlow.AspNetCore" Version="2.2.0" />
<PackageReference Include="ResultFlow.AspNetCore" />
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 ResultFlow.AspNetCore --version 2.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: ResultFlow.AspNetCore, 2.2.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.
#:package ResultFlow.AspNetCore@2.2.0
#: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=ResultFlow.AspNetCore&version=2.2.0
#tool nuget:?package=ResultFlow.AspNetCore&version=2.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
ResultFlow.AspNetCore
ASP.NET Core integration for ResultFlow.
This package provides extension methods to seamlessly convert Result<TValue> and Result objects into ASP.NET Core IActionResult responses with automatic HTTP status code mapping.
📦 Installation
Install the NuGet package:
dotnet add package ResultFlow.AspNetCore
Or via Package Manager:
Install-Package ResultFlow.AspNetCore
?? Quick Start
using ResultFlow.Results;
using ResultFlow.AspNetCore;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
var result = await _userService.GetUserByIdAsync(id);
return result.ToActionResult(); // ? Simple!
}
}
? Features
- ? Automatic HTTP Status Code Mapping - Error types automatically map to correct HTTP status codes
- ? Rich Error Responses - Includes error code, message, details, and metadata
- ? Type Safety - Works with both generic
Result<T>and non-genericResult - ? Zero Boilerplate - Single method call converts results to ActionResults
- ? Comprehensive Logging - Errors include detailed metadata for debugging
?? How It Works
The ToActionResult() extension method automatically:
- On Success ? Returns
200 OKwith the result value - On Failure ? Returns appropriate HTTP status based on error type:
BadRequestError? 400 Bad RequestUnauthorizedError? 401 UnauthorizedForbiddenError? 403 ForbiddenNotFoundError? 404 Not FoundConflictError? 409 ConflictValidationError? 422 Unprocessable EntityInternalServerError? 500 Internal Server Error
?? Usage Examples
Retrieve Operation (GET)
[HttpGet("{id}")]
[ProducesResponseType(typeof(User), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<IActionResult> GetUser(int id)
{
var result = await _userService.GetUserByIdAsync(id);
return result.ToActionResult();
}
Create Operation (POST)
[HttpPost]
[ProducesResponseType(typeof(User), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(409)]
[ProducesResponseType(500)]
public async Task<IActionResult> CreateUser(CreateUserRequest request)
{
var result = await _userService.CreateUserAsync(request);
return result.ToActionResult();
}
Update Operation (PUT)
[HttpPut("{id}")]
[ProducesResponseType(typeof(User), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
[ProducesResponseType(409)]
[ProducesResponseType(500)]
public async Task<IActionResult> UpdateUser(int id, UpdateUserRequest request)
{
var result = await _userService.UpdateUserAsync(id, request);
return result.ToActionResult();
}
Delete Operation (DELETE - Void Operation)
[HttpDelete("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<IActionResult> DeleteUser(int id)
{
var result = await _userService.DeleteUserAsync(id);
return result.ToActionResult();
}
?? Response Format
Success Response (200 OK)
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
Error Response (404 Not Found)
{
"code": "NOT_FOUND",
"message": "The User with identifier '999' was not found.",
"metadata": {
"resourceName": "User",
"identifier": 999
}
}
Error Response (400 Bad Request)
{
"code": "BAD_REQUEST_INVALID_PARAMETER",
"message": "The parameter 'email' is invalid: Invalid email format",
"details": "Email must follow pattern: user@example.com",
"metadata": {
"parameterName": "email",
"providedValue": "invalid-email"
}
}
Error Response (409 Conflict)
{
"code": "CONFLICT_DUPLICATE_RESOURCE",
"message": "A Email with the value 'john@example.com' already exists.",
"metadata": {
"resourceName": "Email",
"conflictingValue": "john@example.com"
}
}
Error Response (500 Internal Server Error)
{
"code": "INTERNAL_SERVER_ERROR",
"message": "An internal server error occurred.",
"details": "System.NullReferenceException: Object reference not set to an instance of an object.",
"metadata": {
"exceptionType": "System.NullReferenceException",
"exceptionMessage": "Object reference not set to an instance of an object."
}
}
?? Service Implementation Example
public class UserService : IUserService
{
private readonly IUserRepository _repository;
private readonly ILogger<UserService> _logger;
public async Task<Result<User>> GetUserByIdAsync(int id)
{
if (id <= 0)
{
_logger.LogWarning("Invalid user ID: {UserId}", id);
return Result<User>.Failed(
BadRequestError.ForInvalidParameter("id", "Must be positive", id)
);
}
var user = await _repository.FindByIdAsync(id);
if (user == null)
{
_logger.LogWarning("User not found: {UserId}", id);
return Result<User>.Failed(
NotFoundError.ByIdentifier("User", id)
);
}
return Result<User>.Ok(user);
}
public async Task<Result<User>> CreateUserAsync(CreateUserRequest request)
{
// Validate input
if (string.IsNullOrWhiteSpace(request.Email))
{
_logger.LogWarning("Email is required");
return Result<User>.Failed(
BadRequestError.ForMissingField("Email")
);
}
if (!IsValidEmail(request.Email))
{
_logger.LogWarning("Invalid email format: {Email}", request.Email);
return Result<User>.Failed(
BadRequestError.ForInvalidParameter("Email", "Invalid format", request.Email)
);
}
// Check for duplicates
var existing = await _repository.FindByEmailAsync(request.Email);
if (existing != null)
{
_logger.LogWarning("Email already exists: {Email}", request.Email);
return Result<User>.Failed(
ConflictError.ForDuplicateResource("Email", request.Email)
);
}
// Create user
try
{
var user = new User
{
Email = request.Email,
Name = request.Name,
CreatedAt = DateTime.UtcNow
};
await _repository.AddAsync(user);
_logger.LogInformation("User created: {UserId}", user.Id);
return Result<User>.Ok(user);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating user");
return Result<User>.Failed(
InternalServerError.FromException(ex, "Error creating user")
);
}
}
public async Task<Result> DeleteUserAsync(int id)
{
var user = await _repository.FindByIdAsync(id);
if (user == null)
{
_logger.LogWarning("User not found: {UserId}", id);
return Result.Failed(
NotFoundError.ByIdentifier("User", id)
);
}
try
{
await _repository.DeleteAsync(user);
_logger.LogInformation("User deleted: {UserId}", id);
return Result.Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting user: {UserId}", id);
return Result.Failed(
InternalServerError.ForOperation("DeleteUser", ex)
);
}
}
private bool IsValidEmail(string email)
=> email.Contains("@") && email.Contains(".");
}
?? HTTP Status Code Mapping
| Error Type | HTTP Code | Response | Description |
|---|---|---|---|
BadRequestError |
400 | Bad Request | Invalid request parameters or format |
UnauthorizedError |
401 | Unauthorized | Missing or invalid authentication |
ForbiddenError |
403 | Forbidden | User lacks required permissions |
NotFoundError |
404 | Not Found | Resource not found |
ConflictError |
409 | Conflict | Resource conflict or duplicate |
ValidationError |
422 | Unprocessable Entity | Validation rule violations |
InternalServerError |
500 | Internal Server Error | Server-side errors |
?? API Reference
ToActionResult - Result<T>
/// <summary>
/// Converts a Result<TValue> to an IActionResult with automatic
/// HTTP status code mapping based on the error type.
/// </summary>
/// <typeparam name="TValue">The type of the success value.</typeparam>
/// <param name="result">The result to convert.</param>
/// <returns>An IActionResult representing the result state.</returns>
/// <remarks>
/// On success, returns 200 OK with the value.
/// On failure, returns appropriate HTTP status code based on error type.
/// </remarks>
public static IActionResult ToActionResult<TValue>(this Result<TValue> result)
ToActionResult - Result (Void)
/// <summary>
/// Converts a non-generic Result to an IActionResult with automatic
/// HTTP status code mapping based on the error type.
/// </summary>
/// <param name="result">The result to convert.</param>
/// <returns>An IActionResult representing the result state.</returns>
/// <remarks>
/// On success, returns 200 OK.
/// On failure, returns appropriate HTTP status code based on error type.
/// </remarks>
public static IActionResult ToActionResult(this Result result)
?? Real-World Example: Complete API
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class ProductsController : ControllerBase
{
private readonly IProductService _service;
private readonly ILogger<ProductsController> _logger;
public ProductsController(IProductService service, ILogger<ProductsController> logger)
{
_service = service;
_logger = logger;
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetProduct(int id)
{
_logger.LogInformation("Getting product with ID: {ProductId}", id);
var result = await _service.GetProductByIdAsync(id);
return result.ToActionResult();
}
[HttpGet]
[ProducesResponseType(typeof(List<Product>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllProducts()
{
_logger.LogInformation("Getting all products");
var result = await _service.GetAllProductsAsync();
return result.ToActionResult();
}
[HttpPost]
[ProducesResponseType(typeof(Product), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CreateProduct(CreateProductRequest request)
{
_logger.LogInformation("Creating new product: {ProductName}", request.Name);
var result = await _service.CreateProductAsync(request);
return result.ToActionResult();
}
[HttpPut("{id}")]
[ProducesResponseType(typeof(Product), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateProduct(int id, UpdateProductRequest request)
{
_logger.LogInformation("Updating product with ID: {ProductId}", id);
var result = await _service.UpdateProductAsync(id, request);
return result.ToActionResult();
}
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> DeleteProduct(int id)
{
_logger.LogInformation("Deleting product with ID: {ProductId}", id);
var result = await _service.DeleteProductAsync(id);
return result.ToActionResult();
}
}
📚 Dependencies
- ResultFlow - Core Result pattern library
- Microsoft.AspNetCore.Mvc.Core - ASP.NET Core MVC framework
?? Contributing
Contributions are welcome! You can:
- ?? Report bugs by creating an Issue
- ?? Suggest features in Discussions
- ?? Submit Pull Requests with improvements
Development Setup
git clone https://github.com/said1993/ResultFlow.git
cd ResultFlow
dotnet build
dotnet test
?? Support
Need help?
- ? Create an Issue
- ?? Start a Discussion
- ?? Visit the Repository
🔗 Related Packages
- ResultFlow - Core library
- ResultFlow.FluentValidation - FluentValidation integration
- ResultFlow.Logging - Structured logging integration
Made with ?? by said1993
Updated: 2025-11-23 19:04:08 UTC
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. 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.
-
net10.0
- ResultFlow (>= 2.2.0)
-
net8.0
- ResultFlow (>= 2.2.0)
-
net9.0
- ResultFlow (>= 2.2.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.