ASP.NET
Updated: September 10, 2025Categories: Languages, Framework, Web, Frontend
Printed from:
ASP.NET Cheatsheet
1. Installation and Setup
.NET SDK Installation
Bash
1234567891011# Download .NET SDK from official website
# Or use package manager
# macOS (Homebrew)
brew install --cask dotnet-sdk
# Windows (Chocolatey)
choco install dotnet-sdk
# Verify installation
dotnet --version
IDE Setup
- Visual Studio: Recommended for Windows
- Visual Studio Code: Cross-platform with .NET extensions
- JetBrains Rider: Cross-platform alternative
Project Creation
Bash
123456789# Create new ASP.NET Core Web App
dotnet new webapp -n MyWebApp
# Create Web API project
dotnet new webapi -n MyApiProject
# Create MVC project
dotnet new mvc -n MyMvcProject
2. Project Structure
MyWebApp/
│
├── Controllers/ # Request handling logic
│ └── HomeController.cs
│
├── Models/ # Data models
│ └── User.cs
│
├── Views/ # UI templates
│ ├── Home/
│ │ └── Index.cshtml
│ └── Shared/
│ └── _Layout.cshtml
│
├── wwwroot/ # Static files
│ ├── css/
│ ├── js/
│ └── images/
│
├── appsettings.json # Configuration
└── Program.cs # Application entry point
3. Controllers
Basic Controller
C#
123456789101112131415161718192021222324252627public class HomeController : Controller
{
// Simple action method
public IActionResult Index()
{
return View();
}
// Action with parameter
public IActionResult Details(int id)
{
var item = _repository.GetById(id);
return View(item);
}
// Different action results
public IActionResult Download()
{
return File("/path/to/file", "application/pdf");
}
public IActionResult RedirectToHome()
{
return RedirectToAction("Index");
}
}
Routing
C#
1234567891011// Attribute Routing
[Route("[controller]/[action]")]
public class UsersController : Controller
{
[HttpGet("{id:int}")]
public IActionResult GetUser(int id) { }
[HttpPost]
public IActionResult CreateUser([FromBody] UserModel model) { }
}
4. Views
Razor Syntax
cshtml
12345678910111213141516@{ // Server-side code block var name = "John"; var currentTime = DateTime.Now; } <h1>Hello, @name!</h1> @if (currentTime.Hour < 12) { <p>Good morning!</p> } @foreach (var item in Model.Items) { <div>@item.Name</div> }
Layout and Partial Views
cshtml
123456789101112131415161718<!-- _Layout.cshtml --> <!DOCTYPE html> <html> <head> @RenderSection("head", required: false) </head> <body> @RenderBody() @await Html.PartialAsync("_Footer") </body> </html> <!-- Partial View: _UserCard.cshtml --> <div class="user-card"> <h3>@Model.Name</h3> <p>@Model.Email</p> </div>
5. Models and Data
Model Definition
C#
12345678910111213141516public class User
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(18, 100)]
public int Age { get; set; }
}
Entity Framework Core
C#
12345678910public class ApplicationDbContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
}
}
6. Routing
Conventional Routing
C#
123456789101112public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
}
Attribute Routing
C#
12345678910[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult GetProduct(int id) { }
[HttpGet("category/{category}")]
public IActionResult GetByCategory(string category) { }
}
7. Middleware
Custom Middleware
C#
123456789101112131415161718192021222324252627282930public class RequestLoggerMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Log request details
Console.WriteLine($"Request: {context.Request.Path}");
await _next(context);
}
}
// Extension method for easy middleware registration
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseRequestLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestLoggerMiddleware>();
}
}
// In Startup/Program
app.UseRequestLogger();
8. Dependency Injection
Service Registration
C#
123456789101112public void ConfigureServices(IServiceCollection services)
{
// Transient: New instance each request
services.AddTransient<IUserService, UserService>();
// Scoped: One instance per HTTP request
services.AddScoped<IDbContext, ApplicationDbContext>();
// Singleton: Single instance for entire application
services.AddSingleton<IConfigService, ConfigService>();
}
9. Configuration
appsettings.json
JSON
1234567891011{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyApp;"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}
Configuration in Code
C#
1234567891011public class Startup
{
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Bind configuration to strongly typed class
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
}
10. Authentication & Authorization
Identity Setup
C#
123456789101112131415161718public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// JWT configuration
});
}
// Policy-based Authorization
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly",
policy => policy.RequireRole("Admin"));
});
11. Web API
API Controller
C#
12345678910111213141516171819[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult GetUsers()
{
var users = _userService.GetAll();
return Ok(users);
}
[HttpPost]
public IActionResult CreateUser([FromBody] UserDto user)
{
var result = _userService.Create(user);
return CreatedAtAction(nameof(GetUser), new { id = result.Id }, result);
}
}
12. Database Operations
EF Core Migrations
Bash
123456789# Create migration
dotnet ef migrations add InitialCreate
# Update database
dotnet ef database update
# Rollback last migration
dotnet ef database update LastGoodMigration
LINQ Queries
C#
12345678910111213// Simple query
var activeUsers = _context.Users
.Where(u => u.IsActive)
.OrderBy(u => u.Name)
.ToList();
// Complex query with includes
var usersWithPosts = _context.Users
.Include(u => u.Posts)
.ThenInclude(p => p.Comments)
.Where(u => u.Posts.Any())
.ToList();
13. Logging and Error Handling
Logging Configuration
C#
123456789101112131415161718192021222324252627public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(configure => {
configure.AddConsole();
configure.AddDebug();
});
}
// In a controller or service
public class UserService
{
private readonly ILogger<UserService> _logger;
public void ProcessUser(User user)
{
try
{
_logger.LogInformation($"Processing user {user.Id}");
// Processing logic
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing user");
}
}
}
14. Testing
Unit Testing
C#
1234567891011121314151617181920public class UserControllerTests
{
[Fact]
public void GetUser_ReturnsUser_WhenUserExists()
{
// Arrange
var mockService = new Mock<IUserService>();
mockService.Setup(x => x.GetUser(1)).Returns(new User { Id = 1 });
var controller = new UserController(mockService.Object);
// Act
var result = controller.GetUser(1);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var user = Assert.IsType<User>(okResult.Value);
Assert.Equal(1, user.Id);
}
}
15. Deployment and Publishing
Bash
123456# Publish for deployment
dotnet publish -c Release -o ./publish
# Create self-contained deployment
dotnet publish -c Release -r linux-x64 --self-contained true
16. Common Commands
Bash
123456789101112131415161718# Create new project
dotnet new webapp
# Restore packages
dotnet restore
# Run project
dotnet run
# Build project
dotnet build
# Run tests
dotnet test
# Add NuGet package
dotnet add package PackageName
17. Best Practices and Patterns
- Use Dependency Injection
- Implement separation of concerns
- Use async/await for I/O-bound operations
- Implement proper error handling
- Use environment-specific configurations
- Secure your application (HTTPS, authentication)
- Use repository and service patterns
- Implement logging and monitoring
- Write unit and integration tests
- Keep controllers thin, move logic to services
Note: This cheatsheet covers core concepts. Always refer to the latest Microsoft documentation for most up-to-date information.
Continue Learning
Discover more cheatsheets to boost your productivity