SoFunction
Updated on 2025-04-14

Implementation solution for creating a unified API interface in C#

1. Technology selection and architecture design

  1. Frame selection

    • Core (6.0+)
    • RESTful API Specification
  2. Core Components

    • Unified response format: Standardized JSON response structure
    • Global exception handling: Unified error returns
    • Version control: API version management
    • Certification Authorization: JWT Bearer Certification
    • Data Verification:Model Validation
    • Logging: Serilog or built-in ILogger
    • Swagger Documentation: OpenAPI specification support
  3. Architectural layering

API Layer (Controllers)
↓
Application Layer (Services)
↓
Domain Layer (Models, Interfaces)
↓
Infrastructure Layer (Repositories)

2. Complete implementation steps

1. Create a project

dotnet new webapi -n UnifiedApiDemo

2. Add NuGet package

dotnet add package 
dotnet add package 
dotnet add package 

3. Core code implementation

1. Unified Response Model

public class ApiResponse<T>
{
    public int Code { get; set; }
    public string Message { get; set; }
    public T Data { get; set; }
    public DateTime Timestamp { get; } = ;

    public static ApiResponse<T> Success(T data) => new() 
    { 
        Code = 200, 
        Message = "Success", 
        Data = data 
    };
    
    public static ApiResponse<object> Error(int code, string message) => new() 
    { 
        Code = code, 
        Message = message 
    };
}

2. Global exception handling middleware

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;

    public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Global exception occurred");
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
         = "application/json";
         = exception switch
        {
            ValidationException => StatusCodes.Status400BadRequest,
            UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
            _ => StatusCodes.Status500InternalServerError
        };

        return (ApiResponse<object>.Error(
            ,
            
        ));
    }
}

3. Unified response packaging filter

public class ApiResponseFilter : IAsyncResultFilter
{
    public async Task OnResultExecutionAsync(
        ResultExecutingContext context, 
        ResultExecutionDelegate next)
    {
        if ( is ObjectResult objResult)
        {
            var apiResponse = ApiResponse<object>.Success();
             = new ObjectResult(apiResponse)
            {
                StatusCode = 
            };
        }
        await next();
    }
}

4. Configure Service ()

var builder = (args);

// Add version control(options =&gt;
{
     = new ApiVersion(1, 0);
     = true;
     = true;
});

// Configure Swagger(c =&gt;
{
    ("v1", new OpenApiInfo { Title = "Unified API", Version = "v1" });
});

// Add a unified response filter(options =&gt;
{
    &lt;ApiResponseFilter&gt;();
});

// Configure JWT authentication()
    .AddJwtBearer(options =&gt; 
    {
         = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "your_issuer",
            ValidateAudience = true,
            ValidAudience = "your_audience",
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.("your_secret_key"))
        };
    });

var app = ();

// Middleware pipeline();
();
&lt;ExceptionMiddleware&gt;();
();
();
();
();

5. Controller example (with version control)

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[Authorize]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ProductDto), 200)]
    public IActionResult GetProduct(int id)
    {
        var product = new ProductDto { Id = id, Name = "Sample Product" };
        return Ok(product);
    }

    [HttpPost]
    [ValidateModel]
    public IActionResult CreateProduct([FromBody] ProductCreateDto dto)
    {
        // Business logic        return CreatedAtAction(nameof(GetProduct), new { id = 1 }, null);
    }
}

6. Model verification example

public class ProductCreateDto
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Range(0, 10000)]
    public decimal Price { get; set; }
}

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!)
        {
            var errors = 
                .Where(e =>  > 0)
                .ToDictionary(
                    kvp => ,
                    kvp => (e => ).ToArray()
                );
            
             = new BadRequestObjectResult(
                ApiResponse<object>.Error(400, "Validation Error", errors)
            );
        }
    }
}

4. Example of operation effect

Successfully responded

{
  "code": 200,
  "message": "Success",
  "data": {
    "id": 1,
    "name": "Sample Product"
  },
  "timestamp": "2024-02-20T12:34:56Z"
}

Error response

{
  "code": 400,
  "message": "Validation Error",
  "data": {
    "Price": ["The field Price must be between 0 and 10000."]
  },
  "timestamp": "2024-02-20T12:35:10Z"
}

V. Expansion suggestions

  1. Performance optimization: Add a response cache mechanism
  2. monitor: Integrated Application Insights
  3. Current limit: Use AspNetCoreRateLimit
  4. DTO Mapping: Use AutoMapper
  5. Unit Testing: Use xUnit/MSTest

This solution provides a complete unified API implementation framework from infrastructure to business logic, which can be extended and adjusted according to specific needs.

This is the article about the implementation plan for creating a unified API interface in C#. For more related content on creating a unified API interface in C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!