ApiBaseFramework 1.0.13
dotnet add package ApiBaseFramework --version 1.0.13
NuGet\Install-Package ApiBaseFramework -Version 1.0.13
<PackageReference Include="ApiBaseFramework" Version="1.0.13" />
<PackageVersion Include="ApiBaseFramework" Version="1.0.13" />
<PackageReference Include="ApiBaseFramework" />
paket add ApiBaseFramework --version 1.0.13
#r "nuget: ApiBaseFramework, 1.0.13"
#:package ApiBaseFramework@1.0.13
#addin nuget:?package=ApiBaseFramework&version=1.0.13
#tool nuget:?package=ApiBaseFramework&version=1.0.13
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:
ApiBaseControllerwith 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
Option 1: Minimal (Swagger + Forwarded Headers)
using ApiBaseFramework;
var builder = WebApplication.CreateBuilder(args);
builder.Services.RegisterApiBase(builder.Configuration);
var app = builder.Build();
app.UseApiBase();
app.MapControllers();
app.Run();
Add to 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: With CORS
using ApiBaseFramework;
using ApiBaseFramework.Cors;
var builder = WebApplication.CreateBuilder(args);
builder.Services.RegisterApiBase(
builder.Configuration,
cors: new ApiBaseCorsOptions
{
AllowedOrigins = new[] { "https://app.example.com", "https://admin.example.com" },
CorsPolicyName = "CorsPolicy",
CorsCredentialsMode = CorsCredentialsMode.CrossDomain
});
var app = builder.Build();
app.UseApiBase();
app.MapControllers();
app.Run();
Option 3: Without Forwarded Headers
builder.Services.RegisterApiBase(
builder.Configuration,
cors: null,
useForwardedHeaders: false);
Option 4: Custom Forwarded Headers (e.g. KnownProxies)
using System.Net;
builder.Services.RegisterApiBase(
builder.Configuration,
cors: null,
useForwardedHeaders: true,
configureForwardedHeaders: o =>
{
o.KnownProxies.Add(IPAddress.Parse("10.0.0.1"));
});
Option 5: Custom Swagger
using Microsoft.OpenApi.Models;
builder.Services.RegisterApiBase(
builder.Configuration,
configureSwagger: info =>
{
info.Description = "Custom description";
info.Contact = new OpenApiContact { Name = "Support", Email = "support@example.com" };
});
UseApiBase() Middleware Order
Call app.UseRouting() before UseApiBase() so the endpoint is resolved before authorization.
app.UseApiBase() configures, in order:
- UseForwardedHeaders (when enabled) — X-Forwarded-For, X-Forwarded-Proto behind a reverse proxy
- UseHttpsRedirection — Redirect HTTP to HTTPS
- UseApiBaseCors — CORS (when
corswas passed toRegisterApiBase) - UseAuthentication — Authentication
- UseAuthorization — Authorization (required for
[Authorize]to work) - UseSwagger / UseSwaggerUI — API docs
- MapControllers — Must be called by your app (e.g. after
UseApiBase)
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
ObjectNotFoundExceptionfor null results - Response Formatting: Boolean and string responses are automatically wrapped
Supported Exceptions
RestBadRequestException→ 400 Bad RequestObjectNotFoundException→ 404 Not FoundUnauthorizedAccessException→ 403 ForbiddenNullReferenceException→ 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 10.0 or higher
- ASP.NET Core
License
MIT
Support
For support, please contact:
- Email: info@waelelazizy.com
- Phone: 00973 33030730
Author
wael EL azizy - waelelazizy.com
| Product | Versions 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. |
-
net10.0
- Microsoft.AspNetCore.Mvc.NewtonsoftJson (>= 10.0.2)
- Newtonsoft.Json (>= 13.0.4)
- Swashbuckle.AspNetCore (>= 6.9.0)
- Swashbuckle.AspNetCore.Annotations (>= 6.9.0)
- Swashbuckle.AspNetCore.Newtonsoft (>= 6.9.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Initial release with RequestAnalyzer, security features, and Swagger integration