.Net 7C#

Creating Your First ASP.NET Core App

ASP.NET Core is a cross-platform framework for building modern web applications using C# and .NET. ASP.NET Core provides a modular and scalable architecture, and it can run on Windows, Linux, and macOS. In this tutorial, we will show you how to create your first ASP.NET Core app step by step.

Table of Contents:
  1. Prerequisites
  2. Create a New ASP.NET Core Project
  3. Run the App
  4. Add a Controller and a View
  5. Add Model Classes and a Database
  6. Add CRUD Operations
  7. Add Validation
  8. Add Authentication and Authorization
  9. Deploy the App
  10. Conclusion

Before we start, you need to install the following software:

  • Visual Studio Code: A free and open-source code editor that supports ASP.NET Core development.
  • .NET SDK: A software development kit that includes the .NET Core runtime and the .NET Core command-line interface (CLI).
  • SQLite: A lightweight and file-based database engine that we will use in this tutorial.
  1. Create a New ASP.NET Core Project

To create a new ASP.NET Core project, follow these steps:

Step 1: Open Visual Studio Code.

Step 2: Click on “Extensions” in the left-hand side menu, search for “C#” and “ASP.NET Core” extensions and install them.

Step 3: Click on “Explorer” in the left-hand side menu, and click on “New Folder” to create a new folder for your project.

Step 4: Open the command palette by pressing Ctrl+Shift+P, and type “dotnet new webapp -o myapp” to create a new ASP.NET Core project named “myapp” in the current folder.

Step 5: Wait for the project to be created, and then open the folder in Visual Studio Code by clicking on “Open Folder” in the welcome screen or by clicking on “File” -> “Open Folder” in the top menu.

  1. Run the App

To run the app, follow these steps:

Step 1: Open the terminal by pressing Ctrl+Shift+` or by clicking on “Terminal” -> “New Terminal” in the top menu.

Step 2: Navigate to the project folder by typing “cd myapp” in the terminal.

Step 3: Type “dotnet run” in the terminal to run the app.

Step 4: Wait for the app to start, and then open a web browser and navigate to “http://localhost:5000” to see the app running.

  1. Add a Controller and a View

To add a controller and a view, follow these steps:

Step 1: Open the terminal and navigate to the project folder.

Step 2: Type “dotnet new controller -name HomeController” in the terminal to add a new controller named “HomeController”.

Step 3: Open the “HomeController.cs” file in the “Controllers” folder, and replace the code with the following:

csharp
using Microsoft.AspNetCore.Mvc;

namespace myapp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Step 4: Type “dotnet new view -name Index” in the terminal to add a new view named “Index”.

Step 5: Open the “Index.cshtml” file in the “Views/Home” folder, and replace the code with the following:





@{
    ViewData["Title"] = "Home Page";
}

<h1>@ViewData["Title"]</h1>
<p>Welcome to my first ASP.NET Core app!</p>

Step 6: Run the app

  1. Add Model Classes and a Database

To add model classes and a database, follow these steps:

Step 1: Open the terminal and navigate to the project folder.

Step 2: Type “dotnet add package Microsoft.EntityFrameworkCore.Sqlite” in the terminal to install the SQLite provider for Entity Framework Core.

Step 3: Type “dotnet add package Microsoft.EntityFrameworkCore.Design” in the terminal to install the design-time services for Entity Framework Core.

Step 4: Type “dotnet ef migrations add InitialCreate” in the terminal to create a migration for the initial database schema.

Step 5: Open the “Startup.cs” file in the root folder, and add the following code to the “ConfigureServices” method:

less
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

Step 6: Create a new folder named “Data” in the root folder, and add a new class named “ApplicationDbContext” with the following code:

using Microsoft.EntityFrameworkCore;

namespace myapp.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<TodoItem> TodoItems { get; set; }
    }
}

Step 7: Create a new folder named “Models” in the root folder, and add a new class named “TodoItem” with the following code:

csharp
namespace myapp.Models
{
    public class TodoItem
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public bool IsComplete { get; set; }
    }
}

Step 8: Open the “appsettings.json” file in the root folder, and add the following code to specify the SQLite database connection string:

appsettings.json
"ConnectionStrings": {
    "DefaultConnection": "DataSource=myapp.db"
},

Step 9: Type “dotnet ef database update” in the terminal to apply the migration and create the database.

  1. Add CRUD Operations

To add CRUD operations, follow these steps:

Step 1: Open the “HomeController.cs” file in the “Controllers” folder, and add the following code to the “Index” method:

csharp
var items = await _context.TodoItems.ToListAsync();
return View(items);

Step 2: Add the following code to the “Create” method:





return View();

Step 3: Add the following code to the “HttpPost Create” method:





_context.TodoItems.Add(item);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));

Step 4: Add the following code to the “Edit” method:





var item = await _context.TodoItems.FindAsync(id);
if (item == null)
{
    return NotFound();
}
return View(item);

Step 5: Add the following code to the “HttpPost Edit” method:

try
{
    _context.Update(item);
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    if (!TodoItemExists(item.Id))
    {
        return NotFound();
    }
    else
    {
        throw;
    }
}
return RedirectToAction(nameof(Index));

Step 6: Add the following code to the “Delete” method:

var item = await _context.TodoItems
    .FirstOrDefaultAsync(m => m.Id == id);
if (item == null)
{
    return NotFound();
}
return View(item);

Step 7: Add the following code to the “HttpPost Delete” method:

var item = await _context.TodoItems.FindAsync(id);
_context.TodoItems.Remove(item);
await _context.SaveChangesAsync;
return RedirectToAction(nameof(Index));

Step 8: Open the “Views/Home” folder, and add a new view named “Create.cshtml” with the following code:

@model myapp.Models.TodoItem

<h1>Create</h1>

<hr />

<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div class="form-group">
                <label asp-for="Title"></label>
                <input asp-for="Title" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="IsComplete"></label>
                <input asp-for="IsComplete" class="form-control" />
            </div>
            <button type="submit" class="btn btn-primary">Create</button>
        </form>
    </div>
</div>

Step 9: Add a new view named “Edit.cshtml” with the following code:

@model myapp.Models.TodoItem

<h1>Edit</h1>

<hr />

<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Title"></label>
                <input asp-for="Title" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="IsComplete"></label>
                <input asp-for="IsComplete" class="form-control" />
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
        </form>
    </div>
</div>

Step 10: Add a new view named “Delete.cshtml” with the following code:

@model myapp.Models.TodoItem

<h1>Delete</h1>

<hr />

<div class="row">
    <div class="col-md-4">
        <form asp-action="Delete">
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Title"></label>
                <input asp-for="Title" class="form-control" disabled />
            </div>
            <div class="form-group">
                <label asp-for="IsComplete"></label>
                <input asp-for="IsComplete" class="form-control" disabled />
            </div>
            <button type="submit" class="btn btn-danger">Delete</button>
        </form>
    </div>
</div>
  1. Run the Application

To run the application, follow these steps:

Step 1: Open the terminal and navigate to the project folder.

Step 2: Type “dotnet run” in the terminal to start the application.

Step 3: Open a web browser and navigate to “http://localhost:5000” to view the application.

Congratulations! You have successfully created your first ASP.NET Core application. You have learned how to create a new project, add dependencies, create a model class and a database, and add CRUD operations. You have also learned how to run the application and view it in a web browser.

In this post, we have covered the basics of creating an ASP.NET Core application. However, there is a lot more to learn, such as using Razor Pages, building APIs, and deploying the

application to the cloud. To continue learning, check out the official documentation and explore other resources such as tutorials and online courses.

In addition to learning the technical aspects of ASP.NET Core, it’s also important to understand best practices for building scalable, maintainable, and secure applications. Some key considerations include using clean code principles, implementing proper authentication and authorization, and testing your code thoroughly.

Lastly, don’t forget to consider SEO when building your ASP.NET Core application. Some tips for optimizing your site for search engines include using descriptive URLs, optimizing your meta tags and content, and ensuring your site is mobile-friendly.

In conclusion, creating your first ASP.NET Core application can seem daunting, but by following the steps outlined in this post and continuing to learn and explore, you can build powerful and scalable web applications with ease. Happy coding!

Back to top button