ASP.Net Core
- Chapter 1: Introduction to ASP.NET Core
- Chapter 2: Building Your First ASP.NET Core Application
- Chapter 3: Controllers and Views
- Chapter 4: Routing and URL Patterns
- Chapter 5: Models and Data Access
- Chapter 6: Middleware and Request Pipeline
- Chapter 7: Dependency Injection and Services
- Chapter 8: Working with Forms and Data Binding
- Chapter 9: Authentication and Authorization
- Chapter 10: Error Handling and Logging
- Chapter 11: Building RESTful APIs with ASP.NET Core
- Chapter 12: Client-Side Development with ASP.NET Core
- Chapter 13: Real-Time Applications with SignalR
- Chapter 14: Deployment and Hosting
- Chapter 15: Testing and Quality Assurance
- Chapter 16: Security Best Practices
- Chapter 17: Advanced Topics
- Chapter 18: Next Steps and Beyond
Tutorials – ASP.Net Core
Chapter 2: Building Your First ASP.NET Core Application
In the previous chapter, you gained a fundamental understanding of what ASP.NET Core is and why it’s a crucial technology for modern web development. Now, it’s time to take your first practical steps in the world of ASP.NET Core. This chapter will guide you through the process of creating your very first ASP.NET Core application, exploring its project structure, and running it to see your work in action.
2.1 Introduction
Before we dive into the hands-on aspects of building an ASP.NET Core application, let’s briefly recap the key concepts from Chapter 1 and set clear objectives for this chapter.
2.1.1 Recap of Chapter 1
In Chapter 1, you learned:
- What ASP.NET Core is, its historical context, and how it differs from its predecessors.
- The key features and advantages that make ASP.NET Core a preferred choice for web development.
- The importance of setting up your development environment to begin working with ASP.NET Core.
2.1.2 Objectives of Chapter 2
The objectives of this chapter are as follows:
- Practical Application: Introduce you to the practical aspects of ASP.NET Core development, where you’ll create a real application.
- Project Creation: Guide you through the process of creating a new ASP.NET Core project, depending on your preferred development environment.
- Understanding Project Structure: Explore the structure of an ASP.NET Core project and explain the purpose of key files and folders.
- Running Your Application: Show you how to build and run your ASP.NET Core application, allowing you to see it in action in a web browser.
2.2 Creating a New ASP.NET Core Project
2.2.1 Importance of Project Templates
Before we create a new project, it’s essential to understand the concept of project templates in ASP.NET Core development.
Project templates serve as starting points for different types of applications, such as web applications, web APIs, or empty projects. They come with preconfigured settings, files, and structures that align with the chosen application type. These templates significantly streamline the initial setup process, saving you time and effort.
2.2.2 Choosing the Right Project Type
ASP.NET Core provides various project templates, each tailored to specific use cases. Understanding the different project types will help you select the most suitable one for your application.
- Web Application: This template is ideal for building full-fledged web applications with user interfaces. It includes the necessary files and folders for creating web pages, handling user input, and rendering views.
- Web API: If you’re developing an API that serves data to other applications or clients, the Web API template is the right choice. It sets up the project for building RESTful APIs with controllers and routes.
- Empty Project: If you prefer to start with a minimal structure and add components as needed, you can opt for an empty project. This template provides a clean slate for custom application setups.
2.2.3 Creating a New Project
Now that you understand the importance of project templates and have chosen the appropriate project type, let’s walk through the process of creating your first ASP.NET Core project.
Using Visual Studio
If you’re using Visual Studio, follow these steps:
- Open Visual Studio.
- Click on “File” in the menu bar and select “New” > “Project.”
- In the “Create a new project” dialog, search for “ASP.NET Core Web Application.”
- Click “Next.”
- Provide a name for your project in the “Project name” field.
- Choose the location where you want to save the project.
- Click “Create.”
- In the “Create a new ASP.NET Core web application” dialog, select the project template that corresponds to your chosen project type (Web Application, Web API, or Empty).
- Click “Create.”
Using Visual Studio Code
If you prefer to use Visual Studio Code, follow these steps:
- Open Visual Studio Code.
- Open the terminal within Visual Studio Code.
- Navigate to the directory where you want to create your project.
- Run the following command to create a new ASP.NET Core project:
dotnet new web -n MyFirstAspNetCoreAppReplace
MyFirstAspNetCoreApp
with your preferred project name. - This command will create a new ASP.NET Core project based on the “web” template.
Using the .NET CLI
For those who prefer the command-line interface, the .NET CLI offers a straightforward way to create a new project.
- Open your terminal or command prompt.
- Navigate to the directory where you want to create your project.
- Run the following command to create a new ASP.NET Core project:
dotnet new web -n MyFirstAspNetCoreAppReplace
MyFirstAspNetCoreApp
with your preferred project name. - This command creates a new ASP.NET Core project based on the “web” template.
Congratulations! You’ve successfully created your first ASP.NET Core project. Now, let’s explore its structure.
2.3 Project Structure and Files
Understanding the structure of your ASP.NET Core project and the roles of key files and folders is essential for effective development. Let’s take a closer look.
2.3.1 Exploring the Project Structure
When you open your newly created project, you’ll notice a structured hierarchy of folders and files. Let’s explore the purpose of each key folder:
- Controllers: This folder is where you’ll define the request-handling logic for your application. Controllers receive incoming HTTP requests, process them, and return responses.
- Views: The Views folder is responsible for rendering HTML and user interfaces. It contains the HTML templates that your application will display to users.
- Models: In the Models folder, you define the data structures or objects that your application will work with. These models represent the data and entities in your application.
- wwwroot: The wwwroot folder is dedicated to storing static files, such as CSS stylesheets, JavaScript scripts, images, and other client-side assets. These files are publicly accessible and play a crucial role in defining your application’s look and behavior.
- appsettings.json: This JSON configuration file allows you to store application-specific settings, such as database connection strings, API keys, or custom configuration values. It’s a central place to manage your application’s configuration.
- Startup.cs: The Startup.cs file is the entry point for configuring your ASP.NET Core application. It defines how the application handles incoming requests and responses. In this file, you set up middleware, configure services, and define routing rules.
2.3.2 Key Files and Folders
Let’s dive deeper into the roles and purposes of these key files and folders.
Controllers
Controllers are a fundamental part of your ASP.NET Core application. They handle incoming HTTP requests, process them, and return appropriate responses. Controllers are responsible for the application’s behavior and logic.
In the Controllers folder, you’ll typically find one or more C# classes that represent different parts of your application. These classes contain methods called “actions,” which are responsible for responding to specific types of requests.
For example, if you’re building a web application, you might have a HomeController with actions that handle requests for different pages, such as the home page, user profile page, or product listing page.
Views
The Views folder is where you define the user interfaces and templates for your application. Views are responsible for rendering HTML content and presenting it to users.
In an ASP.NET Core project, views are typically written using the Razor syntax, a combination of HTML and C#. This allows you to embed dynamic content and data from controllers directly into your views.
Views are closely tied to controllers. Each controller action usually corresponds to a view, and the action’s purpose is to populate the view with data and return it to the client (the user’s web browser).
Models
Models represent the data structures and entities in your application. They define the shape and properties of data that your application works with.
For instance, if you’re building an e-commerce website, you might have models for products, customers, orders, and other entities. These models define the attributes and relationships between different types of data.
In the Models folder, you’ll find C# classes that correspond to your data models. These classes define properties and methods for working with data. Models are crucial for data validation, storage, and retrieval.
wwwroot
The wwwroot folder is where you store static files that are served directly to clients (web browsers). These files include:
- CSS: Cascading Style Sheets (CSS) files that define the visual styling and layout of your web pages.
- JavaScript: JavaScript files that provide interactivity and client-side functionality.
- Images: Graphic files, such as JPEG, PNG, or GIF images used in your application’s design.
- Libraries: Third-party libraries or dependencies that your client-side code relies on.
Placing these files in the wwwroot folder makes them publicly accessible via URLs. For example, a stylesheet in wwwroot/css/style.css would be accessible at https://yourwebsite.com/css/style.css
.
appsettings.json
The appsettings.json file is a configuration file that stores various settings and configurations for your ASP.NET Core application. These settings can include:
- Database connection strings.
- API keys and secrets.
- Custom application settings.
The appsettings.json file is a convenient way to manage configuration in a centralized manner. You can access these settings in your code and use them to customize the behavior of your application.
Startup.cs
The Startup.cs file is the heart of your ASP.NET Core application. It’s where you configure the application’s request processing pipeline, services, and routing.
The key responsibilities of the Startup.cs file include:
- Middleware Configuration: Configuring middleware components that process HTTP requests and responses. Middleware can handle tasks such as authentication, logging, and routing.
- Service Configuration: Registering and configuring services used by your application. Services can include database connections, authentication providers, and custom components.
- Routing Configuration: Defining URL routing rules to map incoming requests to specific controllers and actions.
In summary, the Startup.cs file defines how your ASP.NET Core application processes incoming HTTP requests and how it responds to them.
2.3.3 Understanding the Startup.cs File
The Startup.cs file deserves special attention because of its central role in configuring your ASP.NET Core application. Let’s delve deeper into its contents.
Middleware Configuration
Middleware components are blocks of code that sit in the request processing pipeline. They process incoming HTTP requests and outgoing responses. The order in which middleware components are added to the pipeline matters, as it determines the sequence in which they execute.
In the Startup.cs file, you’ll find a method called Configure
. This method is where you add middleware components to the pipeline. For example, you might add middleware for authentication, logging, and routing.
Here’s an example of configuring middleware for handling exceptions and enabling static files (such as CSS and JavaScript):
app.UseHttpsRedirection(); // Redirect HTTP to HTTPS.{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage(); // Show detailed error pages during development.
}
else
{
app.UseExceptionHandler("/Home/Error"); // Use a custom error page in production.
app.UseHsts(); // Enable HTTP Strict Transport Security (HSTS).
}
app.UseStaticFiles(); // Enable serving static files from wwwroot.
// … Additional middleware configurations …
}
Middleware components are added in the order you specify, and each component performs a specific function in processing requests and responses.
Service Configuration
The Startup.cs file also contains a method called ConfigureServices
. This is where you register and configure services that your application depends on. Services are singletons, scoped, or transient objects that provide functionality to your application.
For example, if your application needs a database connection, you would register a database context as a service in this method. Similarly, you might configure authentication services, dependency injection, or custom services.
Here’s an example of configuring a database context as a service:
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// … Additional service configurations …}
By registering services, you make them available for use throughout your application, and ASP.NET Core takes care of managing their lifecycle.
Routing Configuration
Routing is a critical aspect of ASP.NET Core. It defines how incoming requests are mapped to specific controllers and actions. The Startup.cs file includes routing configuration in the Configure
method.
For instance, you can define routes that specify how URLs should be structured and how they map to controller actions:
app.UseRouting();{
// ... Previous middleware configuration ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: “default”,
pattern: “{controller=Home}/{action=Index}/{id?}”);
});
// … Additional middleware configurations …
}
In this example, the MapControllerRoute
method defines a default route that maps requests to controller actions. For instance, a URL like /Home/Index
will invoke the Index
action of the HomeController
.
Understanding how to configure routing is essential for defining the structure and behavior of your web application’s URLs.
2.3.4 Visualizing the Project Structure
To help you visualize the project structure, here’s a simplified representation:
MyFirstAspNetCoreApp/
│
├── Controllers/
│ ├── HomeController.cs
│ ├── ...
│
├── Views/
│ ├── Home/
│ │ ├── Index.cshtml
│ │ ├── ...
│ ├── ...
│
├── Models/
│ ├── Product.cs
│ ├── ...
│
├── wwwroot/
│ ├── css/
│ │ ├── site.css
│ │ ├── ...
│ ├── js/
│ │ ├── app.js
│ │ ├── ...
│ ├── img/
│ │ ├── logo.png
│ │ ├── ...
│
├── appsettings.json
│
├── Startup.cs
│
├── ...
This visual representation illustrates the organization of your ASP.NET Core project. Each folder serves a specific purpose, and files within them contribute to the functionality and structure of your application.
With a solid understanding of your project’s structure, let’s move on to the next section and learn how to run your application.
2.4 Running Your Application
Creating an application is only the beginning. To see your work in action, you need to build and run your ASP.NET Core application. In this section, we’ll explore the steps required to do just that.
2.4.1 Building the Application
Before you can run your application, you need to build it. Building the application involves compiling your code and generating executable files that can be run by the .NET runtime.
The steps for building your ASP.NET Core application vary depending on your chosen development environment:
Using Visual Studio
If you’re using Visual Studio, building the application is straightforward:
- Open your project in Visual Studio.
- In the toolbar, select the appropriate build configuration (e.g., Debug or Release).
- Click the “Build” menu, then choose “Build Solution.”
Visual Studio will compile your code, and you’ll see build progress and any errors or warnings in the “Error List” window.
Using Visual Studio Code or the .NET CLI
If you’re using Visual Studio Code or the .NET CLI, building your application is done from the command line:
- Open your terminal or command prompt.
- Navigate to the root directory of your ASP.NET Core project.
- Run the following command to build the application:
dotnet build
This command compiles your code and creates the necessary output files. Any build errors or warnings will be displayed in the terminal.
2.4.2 Launching the Application
After successfully building your ASP.NET Core application, it’s time to launch it and see it in action.
Using Visual Studio
If you’re using Visual Studio, launching the application is as simple as pressing the “Start” button or pressing F5
. Visual Studio will build the project (if it hasn’t already been built) and launch the application in your default web browser.
Using Visual Studio Code or the .NET CLI
If you’re using Visual Studio Code or the .NET CLI, you can launch the application using the following steps:
- Open your terminal or command prompt.
- Navigate to the project’s root directory.
- Run the following command to start the application:
dotnet run
This command launches a development server and provides a URL where your application is hosted (usually https://localhost:5001
or https://localhost:5000
). Open this URL in your web browser to access your ASP.NET Core application.
2.4.3 Observing the Result
Once you’ve launched your ASP.NET Core application, it’s time to observe the result. Open your web browser and navigate to the URL where your application is hosted.
Depending on the project template you chose and any modifications you’ve made, you’ll see different content and functionality. For instance:
- If you selected the Web Application template, you might see a home page with a sample layout and navigation.
- If you chose the Web API template, you won’t see a user interface but can test API endpoints using tools like Postman or your browser.
- With an Empty Project, you’ll have a clean slate to build your application from scratch.
Take some time to explore the default content and functionality provided by the project template. This hands-on experience will help you become familiar with the structure and components of an ASP.NET Core application.
2.5 Conclusion of Chapter 2
In this chapter, you’ve embarked on your ASP.NET Core journey by creating your first ASP.NET Core project. You’ve learned the importance of project templates, how to choose the right project type, and the steps to create a new project using Visual Studio, Visual Studio Code, or the .NET CLI.
You’ve also gained a deep understanding of your project’s structure and the roles of key files and folders, such as Controllers, Views, Models, wwwroot, appsettings.json, and Startup.cs. These foundational concepts are crucial as you progress in your ASP.NET Core development journey.
Lastly, you’ve successfully built and launched your application, seeing it in action in a web browser. This hands-on experience has provided valuable insights into how ASP.NET Core handles requests and responses, setting the stage for further exploration in the upcoming chapters.
2.6 Next Steps
As you conclude Chapter 2, you’re well-prepared to dive deeper into the world of ASP.NET Core development. In the following chapters, we’ll explore essential topics such as controllers, views, routing, data access, and more. Each chapter will build upon the knowledge and practical skills you’ve gained so far.
In Chapter 3, we’ll focus on understanding ASP.NET Core controllers and how they handle incoming requests and produce responses. Get ready to explore the heart of your application’s logic and functionality.
Congratulations! You’ve completed Chapter 2 and successfully created and launched your first ASP.NET Core application. In the next chapters, you’ll continue to expand your knowledge and skills in ASP.NET Core development.