ASP Dotnet core- Basics

 



1. Introduction to ASP.NET Core

ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-based, internet-connected applications. Here's how you can start:

Creating a New ASP.NET Core Project

  1. Install .NET SDK: Make sure you have the .NET SDK installed from here.

Create a New Project:
bash
----------------------------------------------------------------------------
dotnet new webapp -o MyFirstApp

cd MyFirstApp

dotnet run


Project Structure Overview

  • Program.cs: The entry point of the application.

  • Startup.cs: Configures services and the app's request pipeline.

  • Pages/: Contains Razor Pages (.cshtml files).

2. Basic Concepts

Hello World Example

Program.cs:
csharp
----------------------------------------------------------------------------
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();


app.MapGet("/", () => "Hello World!");


app.Run();


Run the application:
bash
----------------------------------------------------------------------------
dotnet run


Middleware

Middleware are components that form the request pipeline. They handle requests and responses.

Example:

csharp

----------------------------------------------------------------------------

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();


app.Use(async (context, next) =>

{

    Console.WriteLine("Handling request.");

    await next.Invoke();

    Console.WriteLine("Finished handling request.");

});


app.Run(async context =>

{

    await context.Response.WriteAsync("Hello from middleware!");

});


app.Run();


3. Razor Pages

Razor Pages make it easy to build web apps with clean separation of concerns.

Creating a Razor Page

Add a Razor Page:
bash
----------------------------------------------------------------------------
dotnet new page -n MyPage -o Pages


Edit MyPage.cshtml:
html
----------------------------------------------------------------------------
@page

@model MyFirstApp.Pages.MyPageModel


<h2>Hello, Razor Pages!</h2>


Edit MyPage.cshtml.cs:
csharp
----------------------------------------------------------------------------
using Microsoft.AspNetCore.Mvc.RazorPages;


namespace MyFirstApp.Pages

{

    public class MyPageModel : PageModel

    {

        public void OnGet()

        {

        }

    }

}


4. MVC (Model-View-Controller)

Creating an MVC Application

Create a New MVC Project:
bash
----------------------------------------------------------------------------
dotnet new mvc -o MyMvcApp

cd MyMvcApp

dotnet run


Controllers

Controllers handle HTTP requests and return responses.

Example Controller:

csharp

----------------------------------------------------------------------------

using Microsoft.AspNetCore.Mvc;


namespace MyMvcApp.Controllers

{

    public class HomeController : Controller

    {

        public IActionResult Index()

        {

            return View();

        }

    }

}


Views

Views define the UI of your application.

Example View (Views/Home/Index.cshtml):

html

----------------------------------------------------------------------------

@{

    ViewData["Title"] = "Home Page";

}


<div>

    <h1>Welcome to ASP.NET Core MVC!</h1>

</div>


Models

Models represent the data of your application.

Example Model:

csharp

----------------------------------------------------------------------------

namespace MyMvcApp.Models

{

    public class Product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public decimal Price { get; set; }

    }

}


5. Entity Framework Core

Entity Framework Core (EF Core) is an ORM for .NET that allows developers to work with a database using .NET objects.

Setting Up EF Core

Install EF Core Packages:
bash
----------------------------------------------------------------------------
dotnet add package Microsoft.EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools


Define a DbContext:
csharp
----------------------------------------------------------------------------
using Microsoft.EntityFrameworkCore;


namespace MyMvcApp.Data

{

    public class ApplicationDbContext : DbContext

    {

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)

            : base(options)

        {

        }


        public DbSet<Product> Products { get; set; }

    }

}


Configure the DbContext in Startup.cs:
csharp
----------------------------------------------------------------------------
public void ConfigureServices(IServiceCollection services)

{

    services.AddDbContext<ApplicationDbContext>(options =>

        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


    services.AddControllersWithViews();

}


Add Connection String in appsettings.json:
json
----------------------------------------------------------------------------
"ConnectionStrings": {

    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyMvcApp;Trusted_Connection=True;MultipleActiveResultSets=true"

}


Add and Apply Migrations:
bash
----------------------------------------------------------------------------
dotnet ef migrations add InitialCreate

dotnet ef database update


6. Advanced Concepts

Authentication and Authorization

Add Authentication Services:
csharp
----------------------------------------------------------------------------
public void ConfigureServices(IServiceCollection services)

{

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

            .AddCookie(options =>

            {

                options.LoginPath = "/Account/Login";

            });


    services.AddAuthorization();

    services.AddControllersWithViews();

}


Protecting Routes:
csharp
----------------------------------------------------------------------------
[Authorize]

public IActionResult ProtectedAction()

{

    return View();

}


Dependency Injection

ASP.NET Core has built-in support for dependency injection (DI).

Registering a Service:

csharp

----------------------------------------------------------------------------

public interface IMyService

{

    string GetData();

}


public class MyService : IMyService

{

    public string GetData()

    {

        return "Hello from MyService";

    }

}


public void ConfigureServices(IServiceCollection services)

{

    services.AddSingleton<IMyService, MyService>();

    services.AddControllersWithViews();

}


Injecting a Service:

csharp

----------------------------------------------------------------------------

public class HomeController : Controller

{

    private readonly IMyService _myService;


    public HomeController(IMyService myService)

    {

        _myService = myService;

    }


    public IActionResult Index()

    {

        ViewBag.Message = _myService.GetData();

        return View();

    }

}


7. Deployment

Deploying an ASP.NET Core application involves publishing it to a web server.

Publish the Application:
bash
----------------------------------------------------------------------------
dotnet publish -c Release -o ./publish


  1. Deploy to IIS:

    • Install the ASP.NET Core Hosting Bundle on your server.

    • Configure IIS to serve the application from the published folder.

Conclusion

This is a high-level overview to get you started with ASP.NET Core, covering everything from basic setup to advanced features like authentication and dependency injection. Each section can be expanded with more details and examples, depending on your specific needs and interest areas.

For more in-depth learning, consider exploring the official ASP.NET Core documentation, which provides comprehensive guides and tutorials.


Post a Comment

Previous Post Next Post