Versioning ASP.NET Core Web API

πŸ’‘ Concept Name

API Versioning in ASP.NET Core

πŸ“˜ Quick Intro

As APIs evolve, changes can break older clients. API versioning solves this by allowing multiple versions to coexist, enabling smooth transitions. ASP.NET Core offers built-in support for API versioning via NuGet.

🧠 Analogy / Short Story

Think of an API like a restaurant menu. Over time, dishes change or get renamed. Versioning is like offering old and new menus side by side so loyal customers still get their favorite dishes, while new ones see the updated list.

πŸ”§ Technical Explanation

ASP.NET Core supports API versioning using the `Microsoft.AspNetCore.Mvc.Versioning` package. You can version APIs in several ways:

  • URL Segment: /api/v1/products
  • Query String: /api/products?api-version=1.0
  • HTTP Header: api-version: 1.0
  • Media Type: Accept header with version info

Register API versioning in Program.cs or Startup.cs and annotate controllers with attributes like [ApiVersion("1.0")].

🎯 Purpose & Use Case

  • βœ… Maintain backward compatibility for existing clients
  • βœ… Allow controlled rollout of new API features
  • βœ… Support microservices with independent versioning
  • βœ… Avoid breaking changes in production systems

πŸ’» Real Code Example

Setup API Versioning in ASP.NET Core:


// Program.cs
builder.Services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
});

// Controller
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetV1() => Ok("Product list from v1");
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ProductsV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult GetV2() => Ok("Product list from v2");
}
    

❓ Interview Q&A

Q1: Why is API versioning important?
A: It prevents breaking changes and ensures backward compatibility.

Q2: Which NuGet package enables versioning?
A: Microsoft.AspNetCore.Mvc.Versioning

Q3: Name three versioning strategies?
A: URL segment, Query string, Header-based

Q4: How to set a default version?
A: Use AssumeDefaultVersionWhenUnspecified = true

Q5: Can versioning be combined with Swagger?
A: Yes, via Swashbuckle filters or NSwag

Q6: What does ReportApiVersions do?
A: It adds supported/deprecated versions in response headers

Q7: What is Media Type versioning?
A: Version info sent in the Accept header

Q8: How to version multiple controllers?
A: Use different classes and attributes for each version

Q9: Is API versioning supported in minimal APIs?
A: Not natively as of now, custom handling is needed

Q10: Can we deprecate an API version?
A: Yes, using [Obsolete] or versioning metadata

πŸ“ MCQs

Q1: What is the benefit of API versioning?

  • A. Increase API complexity
  • B. Enable backward compatibility
  • C. Force immediate upgrades
  • D. Disable old endpoints

Q2: Which of these is NOT a versioning method?

  • A. URL Segment
  • B. Query String
  • C. HTTP Method
  • D. Header-based

Q3: What attribute is used to define an API version?

  • A. [RouteVersion]
  • B. [ApiVersion]
  • C. [VersionRoute]
  • D. [HttpVersion]

Q4: What does setting AssumeDefaultVersionWhenUnspecified to true mean?

  • A. API throws error if version is missing
  • B. Uses default version if not provided
  • C. API is skipped
  • D. None of the above

Q5: What file is commonly used to register versioning settings?

  • A. appsettings.json
  • B. Program.cs
  • C. Controller.cs
  • D. launchSettings.json

Q6: What does ReportApiVersions do?

  • A. Logs errors
  • B. Returns supported versions in response headers
  • C. Shows routes in Swagger
  • D. None

Q7: Can you version different controllers independently?

  • A. No
  • B. Yes
  • C. Only in Swagger
  • D. Only using query string

Q8: What is a drawback of URL segment versioning?

  • A. Easy to implement
  • B. Breaks RESTful resource URLs
  • C. Doesn’t work on mobile
  • D. Increases performance

Q9: Which versioning strategy best hides versioning logic?

  • A. URL-based
  • B. Query string
  • C. Header-based
  • D. Extension method

Q10: Can you combine multiple versioning strategies?

  • A. No
  • B. Yes
  • C. Only with filters
  • D. Only in legacy projects

πŸ’‘ Bonus Insight

Versioning is not only about the backend logic. It affects documentation, client SDKs, and DevOps deployment strategies. Plan for versioning early in your API design.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About ASP.NET Core πŸš€

What is ASP.NET Core? πŸ‘‰ Explained
ASP.NET Core vs .NET Framework πŸ‘‰ Explained
Role of Kestrel Server in ASP.NET Core πŸ‘‰ Explained
Middleware & Request Pipeline πŸ‘‰ Explained
Dependency Injection in ASP.NET Core πŸ‘‰ Explained
Program.cs vs Startup.cs πŸ‘‰ Explained
Configuration & appsettings.json πŸ‘‰ Explained
Environment-specific settings πŸ‘‰ Explained
Writing Custom Middleware πŸ‘‰ Explained
Logging in ASP.NET Core πŸ‘‰ Explained
Static File Middleware πŸ‘‰ Explained
Routing fundamentals πŸ‘‰ Explained
Model Binding & Validation πŸ‘‰ Explained
Razor Pages vs MVC πŸ‘‰ Explained
Tag Helpers overview πŸ‘‰ Explained
Filters in MVC (Action, Authorization, Exception) πŸ‘‰ Explained
Web API controllers & content negotiation πŸ‘‰ Explained
Versioning ASP.NET Core Web API πŸ‘‰ Explained
Entity Framework Core introduction πŸ‘‰ Explained
Code-First vs Database-First in EF Core πŸ‘‰ Explained
Migrations in EF Core πŸ‘‰ Explained
LINQ fundamentals πŸ‘‰ Explained
Async/Await and async controllers πŸ‘‰ Explained
Error & Exception Handling Middleware πŸ‘‰ Explained
CORS configuration & usage πŸ‘‰ Explained
Authentication vs Authorization πŸ‘‰ Explained
ASP.NET Core Identity basics πŸ‘‰ Explained
JWT Authentication integration πŸ‘‰ Explained
Caching strategies πŸ‘‰ Explained
Session & State Management πŸ‘‰ Explained
File Upload handling πŸ‘‰ Explained
Health Checks & monitoring πŸ‘‰ Explained
Hosted Services & Background Tasks πŸ‘‰ Explained
Working with IWebHostEnvironment πŸ‘‰ Explained
IWebHostBuilder and WebHost vs Generic Host πŸ‘‰ Explained
Deployment to IIS, Kestrel, Nginx, Docker πŸ‘‰ Explained
Use of HTTP.sys Server πŸ‘‰ Explained
Configuration providers (JSON, env, CLI) πŸ‘‰ Explained
Handling Concurrency in EF Core πŸ‘‰ Explained
Model validation & custom validation πŸ‘‰ Explained
Dependency Injection service lifetimes πŸ‘‰ Explained
Security best practices (HTTPS, HSTS, CSP) πŸ‘‰ Explained
Authorization policies & claims πŸ‘‰ Explained
Rate limiting & request throttling πŸ‘‰ Explained
Health & metrics integration πŸ‘‰ Explained
Swagger/OpenAPI documentation πŸ‘‰ Explained
Blazor fundamentals πŸ‘‰ Explained
Razor Class Libraries (RCL) πŸ‘‰ Explained
SignalR real-time communication πŸ‘‰ Explained
Performance optimization & profiling πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup