Skip to content

ShubhamDalvi1999/FastAPI-to-C-Sharp-Guide

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Employee Admin Portal — ASP.NET Core MVC (Web API) Architecture

This repository implements a simple Employee Administration backend using ASP.NET Core MVC in a Web API style, with Entity Framework Core for data access and a separate Next.js frontend in frontend/.

Overview: .NET, C#, and MVC

🔹 Relation between .NET and C#

  • .NET: A developer platform by Microsoft that provides the CLR (Common Language Runtime), a large Base Class Library (BCL), and tooling to build desktop, web, cloud, mobile, gaming, and IoT apps. It supports multiple languages (C#, VB.NET, F#, ...).
  • C# (C‑Sharp): A modern, object‑oriented language designed by Microsoft that primarily targets .NET. C# compiles to Intermediate Language (IL), which is executed by the .NET CLR. It is simple, safe, and tightly integrated with the .NET ecosystem.
  • 👉 In short: .NET is the platform; C# is a main language on that platform.
    • Analogy: Java ↔ JVM and C# ↔ .NET CLR.

🔹 What is MVC in .NET and C#?

  • MVC (Model–View–Controller) is an architectural pattern (not a language feature) for separating concerns in applications, especially web apps.
  • In .NET (ASP.NET Core MVC):
    • Model: Application data and business rules (e.g., EF Core entities like Employee).
    • View: The UI (Razor views in traditional MVC). In Web API style, the "view" is the serialized HTTP response (JSON).
    • Controller: Handles requests, coordinates work through the Model, and returns a View/Result.
  • In C#: The language itself doesn’t define MVC; you use C# to implement MVC using .NET frameworks like ASP.NET Core MVC.

In this repository we use ASP.NET Core MVC in a Web API style: controllers return JSON consumed by the separate Next.js frontend, not Razor pages.

Analogy: ASP.NET Core MVC vs Python FastAPI

  • Platform/language:
    • ASP.NET Core MVC runs on .NET using C#.
    • FastAPI runs on Python.
  • Routing:
    • ASP.NET Core uses attribute routing on controllers (e.g., [HttpGet]).
    • FastAPI uses function decorators (e.g., @app.get("/path")).
  • Models & validation:
    • ASP.NET Core: C# classes with Data Annotations; EF Core for persistence.
    • FastAPI: Pydantic models for request/response validation; typically SQLAlchemy for persistence.
  • Dependency Injection:
    • ASP.NET Core: built‑in DI container (IServiceCollection, constructor injection).
    • FastAPI: dependency system via Depends.
  • OpenAPI/Swagger:
    • ASP.NET Core: Swagger via Swashbuckle; UI at root in Development.
    • FastAPI: OpenAPI docs auto‑generated; Swagger UI at /docs and ReDoc at /redoc.
  • CORS/middleware:
    • ASP.NET Core: app.UseCors() with configured policies.
    • FastAPI: CORSMiddleware.

Minimal equivalent route example:

[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() => Ok(/* data */);
}
from fastapi import FastAPI

app = FastAPI()

@app.get("/api/employees")
def get_all():
    return {"data": []}

How MVC is applied here

  • Model: Domain/data layer represented by Employee and mapped through EF Core.

    • File: EmployeeAdminPortal/Models/Entities/Employee.cs
      • Properties: Id, Name, Email, Phone, Salary.
      • Uses Data Annotations for validation (e.g., RegularExpression on Phone).
    • File: EmployeeAdminPortal/Data/ApplicationDbContext.cs
      • Inherits DbContext and exposes DbSet<Employee> Employees.
      • Configures table mapping and a filtered unique index on Email.
      • EF Core migrations present under EmployeeAdminPortal/Migrations/.
  • Controller: HTTP layer exposes REST endpoints, orchestrates model operations.

    • File: EmployeeAdminPortal/Controllers/EmployeesController.cs
      • Decorated with [ApiController] and [Route("api/[controller]")] → base route api/employees.
      • Injects ApplicationDbContext via constructor (built-in DI).
      • Endpoints return IActionResult with proper status codes (Ok, CreatedAtAction, NotFound, NoContent, ValidationProblem).
      • Validation:
        • [ApiController] + Data Annotations drive automatic model validation.
        • Explicit TryValidateModel calls for additional checks.
        • Enforces unique Email at both DB (unique index) and app level.
      • Partial updates supported with JsonPatchDocument<Employee> (JSON Patch), enabled by AddNewtonsoftJson() in Program.cs.
  • View: In a Web API, the "View" is the serialized HTTP response (JSON). There are no Razor views here. A separate Next.js UI in frontend/ consumes these JSON endpoints.

Composition and startup

  • File: EmployeeAdminPortal/Program.cs
    • Registers MVC Controllers: builder.Services.AddControllers().AddNewtonsoftJson();
    • Adds Swagger for API exploration in Development (served at the root path).
    • Enables CORS with a permissive default policy (any origin/header/method) for local development and the separate frontend.
    • Configures EF Core SQL Server using connection string key EmployeeDB from appsettings.json.
    • Middleware order: UseSwagger (Dev) → UseHttpsRedirectionUseCorsUseAuthorizationMapControllers.

Routing overview

Attribute routing is used on actions, with constraints for clarity and safety:

  • [HttpGet]GET /api/employees
  • [HttpGet("{id:guid}")]GET /api/employees/{id} (GUID only)
  • [HttpPost]POST /api/employees
  • [HttpPut("{id:guid}")]PUT /api/employees/{id}
  • [HttpPatch("{id:guid}")]PATCH /api/employees/{id} (JSON Patch)
  • [HttpDelete("{id:guid}")]DELETE /api/employees/{id}

Endpoints (summary)

Method Route Description Body/Input
GET /api/employees List all employees
GET /api/employees/{id} Get employee by id (GUID)
POST /api/employees Create new employee Employee JSON
PUT /api/employees/{id} Replace entire employee Employee JSON
PATCH /api/employees/{id} Partially update (JSON Patch) RFC 6902 JSON Patch
DELETE /api/employees/{id} Delete employee

Notes:

  • On POST, the API returns 201 Created with Location header (via CreatedAtAction).
  • On validation failure, it returns 400 with a problem details payload.
  • Unique Email is enforced at DB and API levels; duplicates are rejected with validation errors.

Data access and validation

  • EF Core ApplicationDbContext is registered with scoped lifetime and injected into controllers.
  • OnModelCreating configures:
    • Table name: Employees.
    • Filtered unique index on Email (ignores null/empty) to avoid conflicts for missing emails.
  • Input validation combines Data Annotations on the model and model state checks in the controller.

Swagger (OpenAPI) and developer experience

  • Swagger is configured in Development and served at the app root (e.g., https://localhost:{port}/).
  • You can interact with all endpoints, inspect schemas, and test requests directly in the browser.

CORS and frontend integration

  • A permissive default CORS policy is registered, enabling the separate Next.js frontend under frontend/ to call the API during development.
  • For production, tighten this policy to specific origins, headers, and methods as needed.

Running locally (quick start)

  1. Configure the EmployeeDB connection string in EmployeeAdminPortal/appsettings.json.
  2. Apply database migrations:
    • dotnet ef database update (from EmployeeAdminPortal/)
  3. Run the API:
    • dotnet run --project EmployeeAdminPortal/EmployeeAdminPortal.csproj
  4. Open the Swagger UI at the app root to explore endpoints.

Frontend (optional): see frontend/ for the Next.js client that consumes this API.

Start commands (C# and FastAPI)

  • C# (ASP.NET Core) backend:
# from repo root
dotnet restore
dotnet build

# first time only (apply EF Core migrations)
dotnet tool install --global dotnet-ef  # if not installed
dotnet ef database update --project "EmployeeAdminPortal/EmployeeAdminPortal.csproj"

# run API
dotnet run --project "EmployeeAdminPortal/EmployeeAdminPortal.csproj"
# API: http://localhost:5062 and https://localhost:7010 (Swagger at root in Development)
  • FastAPI (Python) backend:
# from repo root
cd fastapi_backend
python -m venv .venv
. .venv\Scripts\Activate.ps1
pip install -r requirements.txt

# run API
uvicorn main:app --reload --port 7011
# API: http://localhost:7011 (Swagger UI at /docs)
  • Frontend (Next.js) pointing to chosen backend:
cd frontend

# Use C# backend (HTTPS recommended)
echo NEXT_PUBLIC_API_BASE_URL=https://localhost:7010 > .env.local

# Or, use FastAPI backend
echo NEXT_PUBLIC_API_BASE_URL=http://localhost:7011 > .env.local

npm install
npm run dev
# Frontend: http://localhost:3000

HTTP verbs: this API with C# and FastAPI equivalents

Method Route ASP.NET Core (C#) FastAPI (Python)
GET /api/employees [HttpGet] IActionResult GetAllEmployees() @app.get("/api/employees") def get_all(): ...
GET /api/employees/{id} [HttpGet("{id:guid}")] IActionResult GetEmployeeById(Guid id) @app.get("/api/employees/{id}") def get_by_id(id: str): ...
POST /api/employees [HttpPost] IActionResult AddEmployee([FromBody] Employee employee) @app.post("/api/employees") def create(emp: EmployeeIn): ...
PUT /api/employees/{id} [HttpPut("{id:guid}")] IActionResult UpdateEmployee(Guid id, [FromBody] Employee employee) @app.put("/api/employees/{id}") def replace(id: str, emp: EmployeeIn): ...
PATCH /api/employees/{id} [HttpPatch("{id:guid}")] IActionResult PatchEmployee(Guid id, [FromBody] JsonPatchDocument<Employee> patch) @app.patch("/api/employees/{id}") def patch(id: str, ops: list): ...
DELETE /api/employees/{id} [HttpDelete("{id:guid}")] IActionResult DeleteEmployee(Guid id) @app.delete("/api/employees/{id}") def delete(id: str): ...

Notes:

  • In this project, PATCH uses RFC 6902 JSON Patch via JsonPatchDocument<Employee>. In FastAPI, partial updates are commonly modeled with a partial schema or an operations list handled in code.
  • ASP.NET Core uses attribute routing on controller methods; FastAPI uses decorators on functions.

Key files at a glance

  • EmployeeAdminPortal/Program.cs — service registration, middleware pipeline, controller mapping.
  • EmployeeAdminPortal/Data/ApplicationDbContext.cs — EF Core context and model configuration.
  • EmployeeAdminPortal/Models/Entities/Employee.cs — domain model with validation attributes.
  • EmployeeAdminPortal/Controllers/EmployeesController.cs — REST controller implementing CRUD and JSON Patch.
  • EmployeeAdminPortal/Migrations/ — EF Core migrations history.

About

Bridge from FastAPI to C#: ASP.NET Core Web API with EF Core and Swagger.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published