Learning Objectives
- Understand what .NET Core is and how it differs from the .NET Framework.
- Set up the .NET Core 8 SDK and Visual Studio or VS Code.
- Learn about the basic structure of an ASP.NET Core API project.
NET Core Overview
What is .NET Core? .NET Core is an open-source, cross-platform framework for building modern applications. Unlike the .NET Framework, which is limited to Windows, .NET Core can run on Windows, Linux, and macOS, making it more flexible. Starting from .NET 5, Microsoft has unified .NET Core and the traditional .NET Framework into a single platform now referred to simply as .NET, with .NET 8 being the latest version.
Differences from .NET Framework
- Cross-Platform Compatibility: .NET Core runs on multiple platforms, whereas the .NET Framework is Windows-only.
- Performance Improvements: .NET Core is optimized for high performance, making it ideal for scalable web applications.
- Lightweight and Modular: Unlike the monolithic .NET Framework, .NET Core is modular, which means you can use only the libraries you need.
- Deployment Flexibility: .NET Core allows both self-contained and framework-dependent deployments, giving you flexibility based on your needs.
Advantages for API Development
- Cross-Platform: Build APIs that can be hosted on Windows, Linux, or even cloud-native environments.
- High Performance: .NET Core APIs are faster and more lightweight compared to their .NET Framework counterparts.
- Modern Tooling: Improved tooling and command-line interface (CLI) support make building, testing, and deploying APIs easier.
New in .NET 8 .NET 8 introduces Native AOT (Ahead-of-Time) Compilation, which allows you to build self-contained executables with faster startup times and reduced memory usage. This can significantly improve performance in API projects, especially for cloud deployment.
Installation & Setup
Setting Up .NET Core 8 SDK
- Download the SDK: Head over to the official .NET download page and download the latest .NET Core 8 SDK.
- Install the SDK: Run the installer and follow the prompts to install .NET Core.
- Verify Installation: Open a terminal and run the command
dotnet --version
to ensure that .NET Core 8 is installed correctly.
Setting Up the IDE
- Visual Studio: Download the latest version of Visual Studio. During installation, select the ASP.NET and web development workload to get everything you need to build APIs.
- VS Code: For a lightweight IDE, use Visual Studio Code. Install extensions like C# and .NET Core CLI Tools for better development support.
Project Structure
Creating Your First ASP.NET Core API Project
- Step 1: Open a terminal or command prompt.
- Step 2: Run the command:
dotnet new webapi -n MyFirstAPI
This creates a new API project named "MyFirstAPI".
Exploring the Project Structure
- Program.cs: This is where the application starts. In .NET 8, the startup process is simplified, and you can configure all services and middleware in
Program.cs
without a separateStartup.cs
file. - Controllers Folder: Contains API controllers, which handle HTTP requests and send responses. By default, you will see a
WeatherForecastController.cs
that demonstrates a basic API endpoint. - appsettings.json: Used for configuration settings like database connections or application-specific settings.
New in .NET 8 Project Structure
In .NET 8, the startup configuration is even more streamlined. The Program.cs
file uses top-level statements for simplicity. You can set up services, routing, and middleware directly in Program.cs
without extra boilerplate.
Examples
Simple Example: Creating a Basic API Endpoint
Add a new controller named ProductController to handle product data.
Code snippet:
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new List<string> { "Product1", "Product2" });
}
}
Real-Life Example: This endpoint could be part of an e-commerce application, providing a list of products to customers.
Simple Example: Dependency Injection
Register a service in Program.cs:
builder.Services.AddSingleton();
Real-Life Example: Use dependency injection for services like logging or user management to decouple components.
Simple Example: Connecting to SQL Server
Install the Microsoft.Data.SqlClient package and use it in your controller to fetch data from a database.
Code snippet:
using (var connection = new SqlConnection("your_connection_string"))
{
connection.Open();
// Execute queries here
}
Real-Life Example: This could be used to fetch user data in a financial application to verify transactions.
Larger Example: Evolving E-Commerce API
Throughout the chapters, we'll evolve an e-commerce API. Here, we start by setting up the project and creating a ProductController.
Step 1: Create a Product model to represent product data.
Step 2: Create CRUD endpoints for managing products.
[HttpPost]
public IActionResult AddProduct(Product product)
{
// Save product to the database (mock implementation)
return Ok("Product added successfully");
}
Real-Life Example: Imagine a basic product catalog where store admins can add products. This is the foundation for building a fully functional e-commerce platform.
Key Takeaways
- .NET Core 8 offers significant performance and deployment advantages over .NET Framework.
- Cross-Platform and Modular: Develop APIs that can run on different operating systems.
- Simplified Project Structure: The
Program.cs
file handles the setup in a concise manner.
Practical Questions
- What are the main differences between .NET Core and .NET Framework?
- How would you create and run a new ASP.NET Core API project using the CLI?
- How can you use dependency injection to manage service lifetimes in your project?