ASP.
NET Core Guide Notes
1. Fundamentals of ASP.NET Core
ASP.NET Core is a cross-platform framework for building web applications and APIs.
Key components:
- Controller: Handles HTTP requests.
- Middleware: Processing components that run request-response cycles.
- Views: Razor-based templates to render HTML responses.
- Program.cs: The entry point where the application is configured and started.
2. Controllers and Views
Controllers handle incoming requests and return views or JSON responses.
Example Controller:
```csharp
public class HomeController : Controller
public IActionResult Index() => View();
```
Example View (`Index.cshtml`):
```html
<h1>Welcome to ASP.NET Core!</h1>
Page 1
ASP.NET Core Guide Notes
```
3. Dependency Injection (DI)
DI allows the automatic provision of services, promoting loose coupling.
Register services in `Startup.cs`:
```csharp
public void ConfigureServices(IServiceCollection services)
services.AddTransient<IMyService, MyService>();
```
Inject the service in the controller:
```csharp
public class HomeController : Controller
private readonly IMyService _myService;
public HomeController(IMyService myService) => _myService = myService;
```
4. Routing
Page 2
ASP.NET Core Guide Notes
Routing defines URL patterns and their mappings to controllers and actions.
Example route in `Startup.cs`:
```csharp
public void Configure(IApplicationBuilder app)
app.UseRouting();
app.UseEndpoints(endpoints =>
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
```
5. Model Binding
Model binding maps form data or route data to model properties.
Example model:
```csharp
public class Person
public string Name { get; set; }
Page 3
ASP.NET Core Guide Notes
public int Age { get; set; }
```
Controller action to bind the model:
```csharp
public IActionResult Submit(Person person)
// Use the person object
return View();
```
6. Working with Models
Models define the structure and validation logic of data.
Data Annotations for validation:
```csharp
public class Person
[Required]
public string Name { get; set; }
[Range(18, 120)]
Page 4
ASP.NET Core Guide Notes
public int Age { get; set; }
```
7. Views and Razor Syntax
Razor syntax allows embedding server-side code into HTML.
Example Razor code for displaying a model:
```csharp
<h1>@Model.Name</h1>
<p>Age: @Model.Age</p>
```
8. Working with Forms
Use HTML form elements with Razor to capture user input.
```html
<form asp-action="Submit">
<input asp-for="Name" />
<input asp-for="Age" />
<button type="submit">Submit</button>
</form>
```
Page 5
ASP.NET Core Guide Notes
9. Validation
ASP.NET Core uses Data Annotations and ModelState validation.
Example in controller:
```csharp
public IActionResult Submit(Person person)
if (!ModelState.IsValid)
return View(person);
// Proceed if valid
return RedirectToAction("Success");
```
10. Data Annotations and Custom Validation
Data Annotations provide built-in validation like `[Required]`, `[Range]`, etc.
Custom Validation example:
```csharp
public class Person
Page 6
ASP.NET Core Guide Notes
[CustomValidation(typeof(PersonValidator))]
public int Age { get; set; }
public class PersonValidator : ValidationAttribute
public override bool IsValid(object value)
int age = (int)value;
return age >= 18 && age <= 120;
```
11. Database First Approach (EF Core)
EF Core allows using existing databases to generate models and perform CRUD operations.
Example DbContext:
```csharp
public class ApplicationDbContext : DbContext
public DbSet<Person> Persons { get; set; }
```
Page 7
ASP.NET Core Guide Notes
12. CRUD Operations with EF Core
CRUD operations:
Create:
```csharp
context.Persons.Add(new Person { Name = "John", Age = 25 });
context.SaveChanges();
```
Read:
```csharp
var person = context.Persons.Find(1);
```
Update:
```csharp
person.Name = "Updated Name";
context.SaveChanges();
```
Delete:
```csharp
var person = context.Persons.Find(1);
context.Persons.Remove(person);
Page 8
ASP.NET Core Guide Notes
context.SaveChanges();
```
13. Handling Requests and Responses
Model Binding and ModelState validation handle incoming data and return appropriate responses.
Example controller:
```csharp
public IActionResult Submit(Person person)
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok(person);
```
14. Sessions and Cookies
Sessions store data for the duration of a user session.
Example session:
```csharp
Page 9
ASP.NET Core Guide Notes
HttpContext.Session.SetString("UserName", "JohnDoe");
```
Cookies store data that persists beyond the session:
```csharp
Response.Cookies.Append("UserName", "JohnDoe");
```
15. Uploading Files (Images)
File upload controller example:
```csharp
public IActionResult Upload(IFormFile file)
if (file != null)
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
file.CopyTo(stream);
return Ok("File uploaded successfully.");
return BadRequest("File not uploaded.");
Page 10
ASP.NET Core Guide Notes
```
16. State Management
TempData holds data for one request.
Example:
```csharp
TempData["Message"] = "This is a temp message.";
```
ViewData and ViewBag also manage short-term data:
```csharp
ViewBag.Message = "Hello from ViewBag!";
```
17. Working with Dependencies
DI is used to inject services.
Example:
```csharp
public class HomeController : Controller
private readonly IMyService _myService;
Page 11
ASP.NET Core Guide Notes
public HomeController(IMyService myService) => _myService = myService;
```
18. Creating APIs in ASP.NET Core
Controllers with [ApiController]:
```csharp
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
[HttpGet]
public IActionResult Get() => Ok(new { Name = "John", Age = 25 });
```
19. ASP.NET Core Middleware
Middleware pipeline:
```csharp
public void Configure(IApplicationBuilder app)
app.UseMiddleware<CustomMiddleware>();
app.UseRouting();
Page 12
ASP.NET Core Guide Notes
app.UseEndpoints(endpoints => endpoints.MapControllers());
```
20. Configuration and Settings
AppSettings configuration:
```json
"Logging": {
"LogLevel": {
"Default": "Information"
```
21. Localization
Localization example:
```csharp
services.AddLocalization(options => options.ResourcesPath = "Resources");
```
22. Creating and Using Custom Middleware
Page 13
ASP.NET Core Guide Notes
Custom Middleware example:
```csharp
public class CustomMiddleware
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
// Custom logic
await _next(context);
```
23. Authentication & Authorization
Authentication:
```csharp
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
```
Authorization:
```csharp
Page 14
ASP.NET Core Guide Notes
services.AddAuthorization(options =>
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
```
24. Logging & Monitoring
Logging:
```csharp
services.AddLogging(builder => builder.AddConsole());
```
25. Caching
MemoryCache example:
```csharp
services.AddMemoryCache();
var cache = memoryCache.GetOrCreate("cacheKey", entry =>
entry.SlidingExpiration = TimeSpan.FromMinutes(5);
return "cached data";
});
```
Page 15
ASP.NET Core Guide Notes
26. Security
XSS Protection and Content Security Policy:
```csharp
app.UseCspReportOnly(csp => csp.ScriptSources(s => s.Self()));
```
27. Exception Handling in ASP.NET Core
Custom Middleware for Exception Handling:
```csharp
public class CustomExceptionMiddleware
private readonly RequestDelegate _next;
public CustomExceptionMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
try
await _next(context);
catch (Exception ex)
context.Response.StatusCode = 500;
Page 16
ASP.NET Core Guide Notes
await context.Response.WriteAsync("An error occurred.");
```
28. Dependency Injection (DI)
Registering services in `Startup.cs`:
```csharp
services.AddScoped<IMyService, MyService>();
```
Page 17