1. Create a New Project
dotnet new webapi -n MyWebApi // Create a new Web API project
dotnet new mvc -n MyMvcApp // Create a new MVC project
dotnet new razor -n MyRazorApp // Create a new Razor Pages project
dotnet new console -n MyConsoleApp // Create a new Console application
2. Run the Application
dotnet run // Run the application
dotnet watch run // Run with hot reload
dotnet build // Build the project
dotnet publish -c Release // Publish the project for production
3. Program.cs (Minimal API)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
4. Startup.cs (Legacy)
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
5. Dependency Injection
builder.Services.AddScoped<IMyService, MyService>(); // Register a service
builder.Services.AddTransient<IMyService, MyService>(); // Transient lifetime
builder.Services.AddSingleton<IMyService, MyService>(); // Singleton lifetime
6. Middleware
app.Use(async (context, next) => {
await context.Response.WriteAsync("Before Middleware");
await next();
await context.Response.WriteAsync("After Middleware");
});
7. Routing
app.MapGet("/hello", () => "Hello World!"); // Minimal API
app.MapControllers(); // Controller-based routing
8. Controllers
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase {
[HttpGet]
public IActionResult Get() {
return Ok("Hello World!");
}
}
9. Model Binding
[HttpPost]
public IActionResult Post([FromBody] MyModel model) {
return Ok(model);
}
10. Configuration
var configValue = builder.Configuration["MyConfigKey"];
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
11. Environment Variables
var env = builder.Environment;
if (env.IsDevelopment()) {
// Development-specific code
}
12. Logging
builder.Logging.AddConsole();
var logger = app.Logger;
logger.LogInformation("This is a log message");
13. Exception Handling
app.UseExceptionHandler("/error"); // Global exception handler
app.UseStatusCodePages(); // Handle HTTP status codes
14. Custom Middleware
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
await context.Response.WriteAsync("Custom Middleware");
await _next(context);
}
}
app.UseMiddleware<MyMiddleware>();
15. Static Files
app.UseStaticFiles(); // Serve static files from wwwroot
16. File Upload
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file) {
var filePath = Path.Combine("uploads", file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create)) {
await file.CopyToAsync(stream);
}
return Ok(new { filePath });
}
17. Entity Framework Core
public class MyDbContext : DbContext {
public DbSet<MyEntity> MyEntities { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
18. Migrations
dotnet ef migrations add InitialCreate // Create a new migration
dotnet ef database update // Apply migrations to the database
19. Data Annotations
public class MyEntity {
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
20. Asynchronous Programming
public async Task<IActionResult> GetAsync() {
var data = await _context.MyEntities.ToListAsync();
return Ok(data);
}
21. CORS (Cross-Origin Resource Sharing)
builder.Services.AddCors(options => {
options.AddPolicy("AllowAll", builder => {
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
app.UseCors("AllowAll");
22. API Versioning
builder.Services.AddApiVersioning(options => {
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
23. Swagger Documentation
builder.Services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
24. Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "YourIssuer",
ValidAudience = "YourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
};
});
25. Authorization
[Authorize]
public class MySecureController : ControllerBase {
[HttpGet]
public IActionResult GetSecureData() {
return Ok("This is secure data");
}
}
26. Custom Authorization
public class MyAuthorizationHandler : IAuthorizationHandler {
public Task HandleAsync(AuthorizationHandlerContext context) {
// Custom authorization logic
return Task.CompletedTask;
}
}
27. SignalR
builder.Services.AddSignalR();
app.MapHub<MyHub>("/myhub");
28. Background Services
public class MyBackgroundService : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
// Background task logic
await Task.Delay(1000, stoppingToken);
}
}
}
29. Health Checks
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
30. Configuration from JSON
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
31. Configuration from Environment Variables
builder.Configuration.AddEnvironmentVariables();
32. Custom Configuration Section
public class MySettings {
public string Setting1 { get; set; }
}
var mySettings = builder.Configuration.GetSection("MySettings").Get<MySettings>();
33. Razor Pages
public class MyPageModel : PageModel {
public void OnGet() {
// Handle GET request
}
}
34. View Components
public class MyViewComponent : ViewComponent {
public IViewComponentResult Invoke() {
return View();
}
}
35. Tag Helpers
public class MyTagHelper : TagHelper {
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) {
output.Content.SetContent("Hello from Tag Helper!");
}
}
36. ViewData and ViewBag
ViewData["Message"] = "Hello World!";
ViewBag.Message = "Hello World!";
37. TempData
TempData["Message"] = "This is a temporary message.";
38. ModelState Validation
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
39. Custom Model Binder
public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}
40. Action Filters
public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}
public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}
41. Result Filters
public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}
public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}
42. Exception Filters
public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}
43. Resource Filters
public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}
public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}
44. Global Filters
services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});
45. Custom Error Pages
app.UseStatusCodePagesWithReExecute("/error/{0}");
46. Custom Error Handling Middleware
public class ErrorHandlingMiddleware {
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
try {
await _next(context);
} catch (Exception ex) {
// Handle exception
}
}
}
47. Caching
services.AddResponseCaching();
app.UseResponseCaching();
48. Memory Cache
services.AddMemoryCache();
49. Distributed Cache
services.AddDistributedMemoryCache();
50. Session State
services.AddSession();
app.UseSession();
51. Cookie Policy
services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
52. Anti-Forgery Tokens
services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
});
53. HTTPS Redirection
app.UseHttpsRedirection();
54. HSTS (HTTP Strict Transport Security)
app.UseHsts();
55. Content Security Policy
app.UseCsp(options => {
options.DefaultSources(s => s.Self());
});
56. Rate Limiting
services.AddRateLimiter(options => {
options.AddPolicy("RateLimit", policy => {
policy.Limit = 100;
policy.Period = TimeSpan.FromMinutes(1);
});
});
57. Health Checks with Custom Checks
builder.Services.AddHealthChecks()
.AddCheck("MyCustomCheck", () => HealthCheckResult.Healthy());
58. API Documentation with Swagger
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
59. Using View Components
public class MyViewComponent : ViewComponent {
public IViewComponentResult Invoke() {
return View();
}
}
60. Razor View Engine
@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>
61. Partial Views
@Html.Partial("_MyPartialView", model)
62. Layouts
@{
Layout = "_Layout";
}
63. ViewBag and ViewData
ViewBag.Message = "Hello from ViewBag!";
ViewData["Message"] = "Hello from ViewData!";
64. TempData
TempData["Message"] = "This is a temporary message.";
65. ModelState Validation
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
66. Custom Model Binder
public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}
67. Action Filters
public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}
public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}
68. Result Filters
public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}
public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}
69. Exception Filters
public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}
70. Resource Filters
public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}
public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}
71. Global Filters
services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});
72. Custom Error Pages
app.UseStatusCodePagesWithReExecute("/error/{0}");
73. Custom Error Handling Middleware
public class ErrorHandlingMiddleware {
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
try {
await _next(context);
} catch (Exception ex) {
// Handle exception
}
}
}
74. Caching
services.AddResponseCaching();
app.UseResponseCaching();
75. Memory Cache
services.AddMemoryCache();
76. Distributed Cache
services.AddDistributedMemoryCache();
77. Session State
services.AddSession();
app.UseSession();
78. Cookie Policy
services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
79. Anti-Forgery Tokens
services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
});
80. HTTPS Redirection
app.UseHttpsRedirection();
81. HSTS (HTTP Strict Transport Security)
app.UseHsts();
82. Content Security Policy
app.UseCsp(options => {
options.DefaultSources(s => s.Self());
});
83. Rate Limiting
services.AddRateLimiter(options => {
options.AddPolicy("RateLimit", policy => {
policy.Limit = 100;
policy.Period = TimeSpan.FromMinutes(1);
});
});
84. Health Checks with Custom Checks
builder.Services.AddHealthChecks()
.AddCheck("MyCustomCheck", () => HealthCheckResult.Healthy());
85. API Documentation with Swagger
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
86. Using View Components
public class MyViewComponent : ViewComponent {
public IViewComponentResult Invoke() {
return View();
}
}
87. Razor View Engine
@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>
88. Partial Views
@Html.Partial("_MyPartialView", model)
89. Layouts
@{
Layout = "_Layout";
}
90. ViewBag and ViewData
ViewBag.Message = "Hello from ViewBag!";
ViewData["Message"] = "Hello from ViewData!";
91. TempData
TempData["Message"] = "This is a temporary message.";
92. ModelState Validation
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
93. Custom Model Binder
public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}
94. Action Filters
public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}
public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}
95. Result Filters
public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}
public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}
96. Exception Filters
public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}
97. Resource Filters
public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}
public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}
98. Global Filters
services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});
99. Custom Error Pages
app.UseStatusCodePagesWithReExecute("/error/{0}");
100. Custom Error Handling Middleware
public class ErrorHandlingMiddleware {
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
try {
await _next(context);
} catch (Exception ex) {
// Handle exception
}
}
}