RA.Utilities.Api.Response 10.2.0

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

RA.Utilities.Api.Response

NuGet version Codecov NuGet Downloads Documentation GitHub license

RA.Utilities.Api.Response provides a standardized set of models for creating consistent API responses within the RA.Utilities ecosystem. This package includes generic wrappers for success, error, and domain-specific failure scenarios, helping to streamline API development and improve client-side handling.

v10.2.0 changes: The namespace is now RA.Utilities.Api.Response (previously RA.Utilities.Api.Results), constructor overloads were split into convenience and all-argument forms, and responseType is numeric by default. See the migration guide.

v10.2.0 changes: Adds PaymentRequiredResponse for HTTP 402 and raises the RA.Utilities.Core.Constants dependency to 10.1.1, which introduces BaseResponseCode.PaymentRequired, BaseResponseMessages.PaymentRequired, and ResponseType.PaymentRequired (18).

Purpose

When building APIs, it's crucial to have a consistent and predictable response structure. This package provides a set of ready-to-use C# classes that can be returned from your ASP.NET Core applications. These models ensure that every response—whether it's a success, a generic error, or a detailed validation failure—has the same shape, making it easier for clients to parse and handle.

This library is designed to work seamlessly with the other RA.Utilities packages, such as RA.Utilities.Core.Constants for status codes and messages, and RA.Utilities.Api for endpoint helpers and exception handling middleware.

🛠️ Installation

You can install the package via the .NET CLI:

dotnet add package RA.Utilities.Api.Response

Or through the NuGet Package Manager in Visual Studio.

🔗 Dependencies


Usage Example

Here is a simple example of how you can use these response models in an ASP.NET Core controller action.

using Microsoft.AspNetCore.Mvc;
using RA.Utilities.Api.Response;
using RA.Utilities.Core.Constants;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        if (id <= 0)
        {
            // Return a 400 Bad Request with validation details
            var validationError = new BadRequestResult
            {
                PropertyName = "Id",
                ErrorMessage = "Product ID must be a positive number.",
                AttemptedValue = id
            };
            return BadRequest(new BadRequestResponse(validationError));
        }

        // Simulate finding a product
        var product = GetProductFromDatabase(id);

        if (product == null)
        {
            // Return a 404 Not Found
            return NotFound(new NotFoundResponse(new NotFoundResult("Product", id)));
        }

        try
        {
            // Simulate an operation that might fail
            product.Process();
        }
        catch (Exception ex)
        {
            // Return a 500 Internal Server Error
            return StatusCode(500, new ErrorResponse(new ErrorResult
            {
                ErrorCode = "PROCESSING_ERROR",
                ErrorMessage = ex.Message
            }));
        }

        // Return a 200 OK with the product data
        return Ok(new SuccessResponse<Product>(product));
    }
}

Available Result Models

The core of the package is Response<T>, a non-sealed class that serves as a universal wrapper for all API responses. All properties use init-only accessors to ensure immutability after construction.

JSON note: ResponseType is an enum. With default System.Text.Json options, responseType is written as a number (NotFound → 8). Register JsonStringEnumConverter to emit names such as "NotFound".

Response<T>

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public class Response<T>
Properties
Property Type Description
ResponseCode int A code for the response, often mapping to HTTP status codes.
ResponseType ResponseType An enum indicating the type of response (e.g., Success, Error).
ResponseMessage string? A human-friendly message describing the response.
Result T? The actual data payload of the response.

SuccessResponse<T>

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class SuccessResponse<T> : Response<T>

Creates a Response<T> object that produces a Success response, typically corresponding to an HTTP 200 OK status.

Defaults
Property Value
ResponseCode 200 (from BaseResponseCode.Success)
ResponseMessage "Operation completed successfully."
ResponseType ResponseType.Success
Example response:
{
  "responseCode": 200,
  "responseType": 0,
  "responseMessage": "Operation completed successfully.",
  "result": {
    "id": 1,
    "name": "Sample Product"
  }
}

BadRequestResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class BadRequestResponse : Response<BadRequestResult[]>

Creates a Response<BadRequestResult[]> object for validation errors, producing a BadRequest response (HTTP 400).

The Result property contains an array of BadRequestResult objects, where each object details a specific validation failure.

Defaults
Property Value
ResponseCode 400 (from BaseResponseCode.BadRequest)
ResponseMessage "The request is invalid."
ResponseType ResponseType.BadRequest
Result array of BadRequestResult
BadRequestResult

Inherits from ErrorResult.

Property Type Description
PropertyName string? The name of the property that failed validation.
ErrorMessage string The error message (inherited from ErrorResult).
AttemptedValue object? The property value that caused the failure.
ExpectedValue object? The expected value for the property.
ErrorCode string? The specific error code (inherited from ErrorResult).
Example response:
{
  "responseCode": 400,
  "responseType": 12,
  "responseMessage": "The request is invalid.",
  "result": [
    {
      "propertyName": "Email",
      "errorMessage": "Email is not a valid email address.",
      "attemptedValue": "not-an-email",
      "errorCode": "INVALID_FORMAT"
    },
    {
      "propertyName": "Age",
      "errorMessage": "Age must be greater than 18.",
      "attemptedValue": 16,
      "errorCode": "AGE_TOO_LOW"
    }
  ]
}

NotFoundResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class NotFoundResponse : Response<NotFoundResult>

Creates a Response<NotFoundResult> object that produces a NotFound response (HTTP 404). Used when a requested resource could not be found.

Defaults
Property Value
ResponseCode 404 (from BaseResponseCode.NotFound)
ResponseMessage "The requested resource was not found."
ResponseType ResponseType.NotFound
Result NotFoundResult
NotFoundResult

Inherits from ErrorResult.

Property Type Description
Entity string The name of the entity that was not found (e.g., "Product").
Value object The identifier or value used to search for the entity (e.g., 123).
Example response:
{
  "responseCode": 404,
  "responseType": 8,
  "responseMessage": "The requested resource was not found.",
  "result": {
    "entity": "Product",
    "value": 999,
    "errorCode": "NotFound",
    "errorMessage": ""
  }
}

The nested NotFoundResult.ErrorMessage defaults to ""; set it explicitly when clients need text.


ConflictResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class ConflictResponse : Response<ConflictResult>

Creates a Response<ConflictResult> object that produces a Conflict response (HTTP 409). Used when an action cannot be completed because it conflicts with the current state of a resource.

Defaults
Property Value
ResponseCode 409 (from BaseResponseCode.Conflict)
ResponseMessage "A conflict occurred with the current state of the resource."
ResponseType ResponseType.Conflict
Result ConflictResult
ConflictResult

Inherits from ErrorResult.

Property Type Description
Entity string The name of the entity causing the conflict.
Value object The value of the entity that caused the conflict.
Example response:
{
  "responseCode": 409,
  "responseType": 9,
  "responseMessage": "A conflict occurred with the current state of the resource.",
  "result": {
    "entity": "User",
    "value": "existing@example.com",
    "errorMessage": ""
  }
}

The nested ConflictResult.ErrorMessage defaults to ""; set it explicitly when clients need text.


UnauthorizedResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class UnauthorizedResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for an unauthorized request (HTTP 401). Used when the request requires user authentication.

Defaults
Property Value
ResponseCode 401 (from BaseResponseCode.Unauthorized)
ResponseMessage "Authentication failed or is missing."
ResponseType ResponseType.Unauthorized
Result ErrorResult
Example response:
{
  "responseCode": 401,
  "responseType": 10,
  "responseMessage": "Authentication failed or is missing.",
  "result": null
}

PaymentRequiredResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class PaymentRequiredResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for a payment required error (HTTP 402). Used when an authenticated caller must pay before accessing the resource — a paywall, an exhausted prepaid balance, or a quota that only a paid plan unlocks.

Constructors: (ErrorResult? result = null) applies the standard 402 code, message, and type; (int responseCode, string responseMessage) accepts custom values with a null result; (ErrorResult result, int? responseCode, string responseMessage = "") accepts an explicit payload (responseCode: null falls back to 402, and an empty message is kept as "").

Defaults
Property Value
ResponseCode 402 (from BaseResponseCode.PaymentRequired)
ResponseMessage "Payment is required to access this resource."
ResponseType ResponseType.PaymentRequired
Result ErrorResult
Example response:
{
  "responseCode": 402,
  "responseType": 18,
  "responseMessage": "Payment is required to access this resource.",
  "result": null
}

ForbiddenResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class ForbiddenResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for a forbidden request (HTTP 403). Used when the server understands the request but refuses to authorize it.

Defaults
Property Value
ResponseCode 403 (from BaseResponseCode.Forbidden)
ResponseMessage "You do not have permission to access this resource."
ResponseType ResponseType.Forbidden
Result ErrorResult
Example response:
{
  "responseCode": 403,
  "responseType": 14,
  "responseMessage": "You do not have permission to access this resource.",
  "result": null
}

TooManyRequestsResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class TooManyRequestsResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for a rate limit error (HTTP 429). Used when the client has sent too many requests in a given amount of time.

Defaults
Property Value
ResponseCode 429 (from BaseResponseCode.TooManyRequests)
ResponseMessage "Too many requests. Please try again later."
ResponseType ResponseType.TooManyRequests
Result ErrorResult

UnprocessableResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class UnprocessableResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object that produces an Unprocessable response (HTTP 422). Used when the server understands the content type but was unable to process the contained instructions.

Defaults
Property Value
ResponseCode 422 (from BaseResponseCode.Unprocessable)
ResponseMessage "Unprocessable entity."
ResponseType ResponseType.Unprocessable
Result ErrorResult

ServiceUnavailableResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class ServiceUnavailableResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for a service unavailable error (HTTP 503). Used when the server is temporarily unable to handle the request.

Defaults
Property Value
ResponseCode 503 (from BaseResponseCode.ServiceUnavailable)
ResponseMessage "The service is temporarily unavailable. Please try again later."
ResponseType ResponseType.ServiceUnavailable
Result ErrorResult

GatewayTimeoutResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class GatewayTimeoutResponse : Response<ErrorResult>

Creates a Response<ErrorResult> object for a gateway timeout error (HTTP 504). Used when the server, acting as a gateway or proxy, did not receive a timely response from the upstream server.

Defaults
Property Value
ResponseCode 504 (from BaseResponseCode.GatewayTimeout)
ResponseMessage "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server."
ResponseType ResponseType.GatewayTimeout
Result ErrorResult

ErrorResponse

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public sealed class ErrorResponse : Response<ErrorResult>

Creates a Response<ErrorResult> that produces a generic Error response (HTTP 500). This response type is used for unexpected server-side errors and serves as a fallback for unhandled exceptions.

Defaults
Property Value
ResponseCode 500 (from BaseResponseCode.InternalServerError)
ResponseMessage "Something happened on our end."
ResponseType ResponseType.Error
Result ErrorResult
Example response:
{
  "responseCode": 500,
  "responseType": 11,
  "responseMessage": "Something happened on our end.",
  "result": {
    "errorCode": "InternalServerError",
    "errorMessage": "An unexpected error occurred on the server."
  }
}

ErrorResult

Namespace: RA.Utilities.Api.Response<br> Package: RA.Utilities.Api.Response<br> Source: RA.Utilities.Api.Response

public class ErrorResult

Represents a result containing error information. Serves as the base for BadRequestResult, NotFoundResult, and ConflictResult.

Property Type Description
ErrorCode string? The machine-readable error code.
ErrorMessage string The human-readable description of the error.

Response Type Reference

All response types and their defaults:

Response Class HTTP Code ResponseType Result Type
SuccessResponse<T> 200 Success T
BadRequestResponse 400 BadRequest BadRequestResult[]
UnauthorizedResponse 401 Unauthorized ErrorResult
PaymentRequiredResponse 402 PaymentRequired ErrorResult
ForbiddenResponse 403 Forbidden ErrorResult
NotFoundResponse 404 NotFound NotFoundResult
ConflictResponse 409 Conflict ConflictResult
UnprocessableResponse 422 Unprocessable ErrorResult
TooManyRequestsResponse 429 TooManyRequests ErrorResult
ErrorResponse 500 Error ErrorResult
ServiceUnavailableResponse 503 ServiceUnavailable ErrorResult
GatewayTimeoutResponse 504 GatewayTimeout ErrorResult

Contributing

Contributions are welcome! If you have a suggestion or find a bug, please open an issue to discuss it.

Pull Request Process

  1. Fork the Repository: Start by forking the RA.Utilities repository.
  2. Create a Branch: Create a new branch for your feature or bug fix from the main branch. Please use a descriptive name (e.g., feature/add-new-exception or fix/readme-typo).
  3. Make Your Changes: Write your code, ensuring it adheres to the existing coding style. Add or update XML documentation for any new public APIs.
  4. Update README: If you are adding a new exception or changing functionality, please update the README.md file accordingly.
  5. Submit a Pull Request: Push your branch to your fork and open a pull request to the main branch of the original repository. Provide a clear description of the changes you have made.

Coding Standards

  • Follow the existing coding style and conventions used in the project.
  • Ensure all public members are documented with clear XML comments.
  • Keep changes focused. A pull request should address a single feature or bug.

Thank you for contributing!

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 (2)

Showing the top 2 NuGet packages that depend on RA.Utilities.Api.Response:

Package Downloads
RA.Utilities.Api

Provides a collection of essential utilities for building robust and consistent ASP.NET Core APIs. This package includes endpoint registration helpers, standardized response models, and exception handling middleware to streamline development and promote best practices.

RA.Utilities.OpenApi

This package provides utilities to generate and transform OpenAPI documents for ASP.NET Core web APIs.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.2.0 63 10/28/2026
10.1.0 135 10/18/2026
10.0.0 155 9/17/2026