ApiBaseFramework 1.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package ApiBaseFramework --version 1.0.2
                    
NuGet\Install-Package ApiBaseFramework -Version 1.0.2
                    
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="ApiBaseFramework" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ApiBaseFramework" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="ApiBaseFramework" />
                    
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 ApiBaseFramework --version 1.0.2
                    
#r "nuget: ApiBaseFramework, 1.0.2"
                    
#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 ApiBaseFramework@1.0.2
                    
#: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=ApiBaseFramework&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=ApiBaseFramework&version=1.0.2
                    
Install as a Cake Tool

ApiBaseFramework

A comprehensive .NET framework for building robust API applications with built-in Swagger integration, standardized response handling, and utility helpers.

Features

  • Swagger Integration: Complete Swagger/OpenAPI documentation with JWT Bearer authentication support
  • Base Controller: ApiBaseController with standardized error handling and response formatting
  • Response Models: Standardized API response models with consistent structure
  • Custom Exceptions: Built-in exceptions for common API scenarios
  • Helper Classes: Encryption, validation, calculations, and utility functions
  • Extension Methods: Rich set of string, collection, and JSON extension methods
  • Regex Patterns: Pre-defined regex patterns for common validations

Getting Started

Installation

dotnet add package ApiBaseFramework

Basic Setup

using ApiBaseFramework;

// In Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register ApiBaseFramework services (includes Swagger)
builder.Services.Register(builder.Configuration);

var app = builder.Build();

// Enable Swagger UI (add this in your middleware pipeline)
app.UseSwaggerUI();

// Configure other middleware...

app.Run();

Add the following to your appsettings.json:

{
  "Swagger": {
    "Title": "My API",
    "Version": "v1",
    "Description": "Optional API description",
    "Contact": {
      "Name": "Your Name",
      "Email": "contact@example.com",
      "Url": "https://example.com"
    }
  }
}
Option 2: Using Explicit Configuration
using ApiBaseFramework;

var builder = WebApplication.CreateBuilder(args);

// Register Swagger with explicit configuration
builder.Services.AddSwagger(
    title: "My API",
    version: "v1",
    description: "My awesome API description");

var app = builder.Build();

// Enable Swagger UI
app.UseSwaggerUI();

app.Run();
Option 3: Custom Swagger Configuration
using ApiBaseFramework;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Register with custom configuration
builder.Services.Register(builder.Configuration, swaggerInfo =>
{
    swaggerInfo.Description = "Custom description";
    swaggerInfo.Contact = new OpenApiContact
    {
        Name = "Support Team",
        Email = "support@example.com"
    };
});

var app = builder.Build();

// Use Swagger UI with custom route (default is "swagger")
app.UseSwaggerUI(routePrefix: "api-docs");

app.Run();

Swagger Features

The Swagger integration includes:

  • JWT Bearer Authentication: Automatically configured with authorization support
  • Language Support: Accept-Language header parameter with supported cultures
  • Optional Route Parameters: Proper handling of optional route parameters
  • XML Comments: Automatically includes XML documentation if available
  • Customizable UI: Enhanced Swagger UI with filters, deep linking, and more

Accessing Swagger UI

After setup, access Swagger UI at:

  • Default: https://your-domain/swagger
  • Custom: https://your-domain/{routePrefix} (if you specified one)

XML Comments Support

To include XML comments in Swagger documentation, enable XML documentation in your .csproj:

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

Then document your controllers and actions:

/// <summary>
/// Gets user information
/// </summary>
/// <param name="id">User identifier</param>
/// <returns>User information</returns>
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
    // ...
}

ApiBaseController

The ApiBaseController provides standardized error handling and response formatting for all API endpoints.

Usage

using ApiBaseFramework;
using Microsoft.AspNetCore.Mvc;

public class UsersController : ApiBaseController
{
    [HttpGet("{id}")]
    public async Task<ActionResult> GetUser(int id)
    {
        return await RUNAsync(async () =>
        {
            // Your business logic here
            var user = await _userService.GetUserAsync(id);
            return user; // Automatically wrapped in ResponseModel_200
        });
    }

    [HttpPost]
    public async Task<ActionResult> CreateUser(CreateUserRequest request)
    {
        return await RUNAsync(async () =>
        {
            // Your business logic here
            var newUser = await _userService.CreateUserAsync(request);
            return newUser;
        });
    }
}

Features

  • Automatic Error Handling: Catches and formats exceptions appropriately
  • Standardized Responses: All responses follow consistent structure
  • Model Validation: Automatic validation check before executing action
  • Null Handling: Automatically throws ObjectNotFoundException for null results
  • Response Formatting: Boolean and string responses are automatically wrapped

Supported Exceptions

  • RestBadRequestException → 400 Bad Request
  • ObjectNotFoundException → 404 Not Found
  • UnauthorizedAccessException → 403 Forbidden
  • NullReferenceException → 500 Internal Server Error
  • General Exception → 500 Internal Server Error

Response Models

ResponseModel_200<T>

Standard success response model:

// Returns: 
// {
//   "StatusCode": 200,
//   "Status": "OK",
//   "Data": { ... }
// }

ErrorResponseModel

Standard error response model:

// Returns:
// {
//   "StatusCode": 400,
//   "Status": "BadRequest",
//   "ErrorDescription": "Error message",
//   "Exception": { ... }
// }

BooleanRresponse

Wrapper for boolean responses:

// Returns boolean values in standardized format

TextResponse

Wrapper for text/string responses:

// Returns string values in standardized format

Helper Classes

EncryptionHelper

Encrypt and decrypt strings:

using ApiBaseFramework.Helpers;

var encrypted = EncryptionHelper.Encrypt("sensitive data");
var decrypted = EncryptionHelper.Decrypt(encrypted);

KsaValidator

Validate civil ID numbers programmatically:

using ApiBaseFramework.Validator;

bool isValid = KsaValidator.IsValid("1234567890");

KsaId (Validation Attribute)

Use as a validation attribute for any KSA ID (Saudi or Non-Saudi):

using ApiBaseFramework.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [KsaId(ErrorMessage = "Invalid KSA ID")]
    public string KsaIdNumber { get; set; }
    
    // Or use with Required attribute
    [Required]
    [KsaId(ErrorMessage = "KSA ID is required and must be valid")]
    public string NationalId { get; set; }
}

The attribute validates:

  • 10-digit format
  • Correct prefix (1 for Saudi, 2 for Non-Saudi)
  • Checksum algorithm validity

SaudiNationalId (Validation Attribute)

Use specifically for Saudi National Id numbers (must start with 1):

using ApiBaseFramework.Validator;
using System.ComponentModel.DataAnnotations;

public class SaudiUserModel
{
    [SaudiNationalId(ErrorMessage = "Invalid Saudi National Id")]
    public string SaudiNationalIdNumber { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Saudi National Id is required")]
    [SaudiNationalId(ErrorMessage = "Must be a valid Saudi National Id starting with 1")]
    public string NationalId { get; set; }
}

The SaudiNationalId attribute validates:

  • All standard Civil ID validations (format, checksum)
  • Additional check: Must start with digit 1 (Saudi nationals only)

NonSaudiIqama (Validation Attribute)

Use specifically for Non-Saudi Iqama numbers (must start with 2):

using ApiBaseFramework.Validator;
using System.ComponentModel.DataAnnotations;

public class NonSaudiUserModel
{
    [NonSaudiIqama(ErrorMessage = "Invalid Non-Saudi Iqama")]
    public string IqamaNumber { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Non-Saudi Iqama is required")]
    [NonSaudiIqama(ErrorMessage = "Must be a valid Non-Saudi Iqama starting with 2")]
    public string IqamaId { get; set; }
}

The NonSaudiIqama attribute validates:

  • All standard Civil ID validations (format, checksum)
  • Additional check: Must start with digit 2 (Non-Saudi nationals only)

Note: All attributes allow null/empty values by default. Use [Required] if the field is mandatory.

Static Validator Methods

You can also validate programmatically:

using ApiBaseFramework.Validator;

// Validate any Civil ID (Saudi or Non-Saudi)
bool isValid = KsaValidator.IsValid("1234567890");

// Validate specifically for Saudi National Id (must start with 1)
bool isSaudiValid = SaudiNationalIdValidator.IsValid("1234567890");

// Validate specifically for Non-Saudi Iqama (must start with 2)
bool isNonSaudiValid = NonSaudiIqamaValidator.IsValid("2234567890");

// Validate email address
bool isValidEmail = EmailValidator.IsValid("user@example.com");

Email (Validation Attribute)

Use for email address validation:

using ApiBaseFramework.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [Email(ErrorMessage = "Invalid email address")]
    public string EmailAddress { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Email is required")]
    [Email(ErrorMessage = "Must be a valid email address")]
    public string ContactEmail { get; set; }
}

The Email attribute validates:

  • Valid email format using regex pattern
  • Standard email format requirements

Note: The attribute allows null/empty values by default. Use [Required] if the field is mandatory.

CardExpression

Card number processing:

using ApiBaseFramework.Helpers;

string issuerCardRefId = CardExpression.GetIssuerCardRefId(cardNo, expiryDate);
string cardNumber = CardExpression.GetCardNumber(issuerCardRefId);

APRCalculationHelper

Financial calculations for APR (Annual Percentage Rate):

using ApiBaseFramework.Helpers;

double apr = APRCalculationHelper.GetAPRValueBaseeta(amount, tenure, rate, date);
double pmt = APRCalculationHelper.GetPMTCompound(pv, per, r);

RandomGen

Generate random strings and numbers:

using ApiBaseFramework.Helpers;

string randomString = RandomGen.String(length: 10);
string numbersOnly = RandomGen.String(length: 6, NumbersOnly: true);
int randomInt = RandomGen.INT(from: 1, to: 100);

EmailValidationAttribute

Email validation attribute:

using ApiBaseFramework.Helpers;

public class UserModel
{
    [EmailValidation]
    public string Email { get; set; }
}

Extension Methods (AppExtensions)

String Extensions

using ApiBaseFramework;

// Check if empty/not empty
bool isEmpty = myString.IsEmpty();
bool isNotEmpty = myString.IsNotEmpty();

// Safe transformations
string upper = myString.SafeToUpper();
string lower = myString.SafeToLower(defaultValue: "default");

// String manipulation
string capitalized = myString.Capitalize();
string slug = myString.Slugify();
string masked = myString.Mask(showLast: 4);
string maskedEmail = myString.MaskEmail();

// Parsing
var list = "1,2,3,4".SplitToList(delimiter: ',');
bool? result = "1,2,3".SplitToIntList(out List<int> intList);

// HTML stripping
string clean = htmlString.StripHtml();

// Email validation
bool isValid = email.IsEmailValid();

Collection Extensions

// NameValueCollection to Dictionary
var dict = nameValueCollection.ToDictionary();

JSON Extensions

// Serialize to JSON
string json = myObject.ToJson();
string formattedJson = myObject.ToJson(formatting: Formatting.Indented);

// Convert to JToken
var jArray = myObject.ToJArray();
var jObject = myObject.ToJObject();

Boolean Extensions

// Convert to bit (1 or 0)
int bit = myBool.BIT();

// Convert to Yes/No
string yesNo = myBool.Yes_No();

// Translate
string result = myBool.Translate("True", "False");

DataTable Extensions

List<MyModel> models = dataTable.ToGenericList<MyModel>(row => 
    new MyModel 
    { 
        Id = row.Field<int>("Id") 
    });

Regex Patterns (RegexExp)

Pre-defined regex patterns for common validations:

using ApiBaseFramework.Models;

// Civil ID patterns
Regex.IsMatch(id, RegexExp.Saudi);
Regex.IsMatch(id, RegexExp.CivilId);

// Financial patterns
Regex.IsMatch(iban, RegexExp.IBAN);

// Contact patterns
Regex.IsMatch(mobile, RegexExp.Mobile);
Regex.IsMatch(phone, RegexExp.Phone);

// Security patterns
Regex.IsMatch(password, RegexExp.Password);
Regex.IsMatch(pin, RegexExp.PIN);

// Date patterns
Regex.IsMatch(date, RegexExp.Date_G); // Gregorian
Regex.IsMatch(date, RegexExp.Date_H); // Hijri

// Text patterns
Regex.IsMatch(text, RegexExp.Alphabetical);
Regex.IsMatch(text, RegexExp.Alphabetical_En);
Regex.IsMatch(text, RegexExp.Alphabetical_AR);

Custom Exceptions

RestBadRequestException

Thrown when request validation fails:

using ApiBaseFramework.Models.Exceptions;

throw new RestBadRequestException();

ObjectNotFoundException

Thrown when a requested resource is not found:

using ApiBaseFramework.Models.Exceptions;

if (user == null)
    throw new ObjectNotFoundException();

Requirements

  • .NET 9.0 or higher
  • ASP.NET Core

License

MIT

Author

wael EL azizy - waelelazizy.com

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.0.13 385 1/28/2026
1.0.12 115 1/27/2026
1.0.11 121 1/25/2026
1.0.10 117 1/24/2026
1.0.7 132 1/24/2026
1.0.6 109 1/24/2026
1.0.5 138 1/21/2026
1.0.3 261 11/3/2025
1.0.2 223 11/3/2025

Initial release with RequestAnalyzer, security features, and Swagger integration