1. Create a New Project


dotnet new mvc -n MyMvcApp // Create a new MVC project

2. Run the Application


dotnet run // Run the application
dotnet build // Build the project
dotnet publish -c Release // Publish the project for production

3. Controllers


public class MyController : Controller {
public IActionResult Index() {
return View();
}
}

4. Actions


public class MyController : Controller {
public IActionResult Index() {
return View();
}

[HttpPost]
public IActionResult Create(MyModel model) {
return RedirectToAction("Index");
}
}

5. Views


@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>

6. Razor Syntax


@{
var name = "John Doe";
}
<h1>Hello, @name!</h1>

7. Model Binding


public class MyController : Controller {
[HttpPost]
public IActionResult Create([Bind("Name,Description")] MyModel model) {
return RedirectToAction("Index");
}
}

8. Validation


public class MyModel {
[Required]
public string Name { get; set; }

[Required]
public string Description { get; set; }
}

9. Routing


routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");

10. Areas


public class MyAreaRegistration : AreaRegistration {
public override string AreaName {
get { return "MyArea"; }
}

public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
"MyArea_default",
"MyArea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional });
}
}

11. Layouts


@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

12. Partial Views


@Html.Partial("_MyPartialView", model)

13. Child Actions


[ChildActionOnly]
public ActionResult MyChildAction() {
return PartialView("_MyPartialView", model);
}

14. Sections


@RenderSection("MySection", required: false)

15. Bundling and Minification


bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/site.css"));

16. Authentication


[Authorize]
public class MyController : Controller {
public IActionResult Index() {
return View();
}
}

17. Authorization


[Authorize(Roles = "Admin")]
public class MyController : Controller {
public IActionResult Index() {
return View();
}
}

18. Custom Authorization


public class MyAuthorizeAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
// Custom authorization logic
return true;
}
}

19. Error Handling


[HandleError]
public class MyController : Controller {
public IActionResult Index() {
return View();
}
}

20. Custom Error Pages


<customErrors mode="On" defaultRedirect="~/Error">
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

21. Logging


public class MyController : Controller {
private readonly ILogger _logger;

public MyController(ILogger logger) {
_logger = logger;
}

public IActionResult Index() {
_logger.LogInformation("Index action executed");
return View();
}
}

22. Dependency Injection


public class MyController : Controller {
private readonly IMyService _myService;

public MyController(IMyService myService) {
_myService = myService;
}
}

23. ViewData and ViewBag


ViewData["Message"] = "Hello from ViewData!";
ViewBag.Message = "Hello from ViewBag!";

24. TempData


TempData["Message"] = "This is a temporary message.";

25. ModelState Validation


if (!ModelState.IsValid) {
return View(model);
}

26. Custom Model Binder


public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}

27. Action Filters


public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}

public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}

28. Result Filters


public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}

public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}

29. Exception Filters


public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}

30. Resource Filters


public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}

public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}

31. Global Filters


services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});

32. Custom Error Pages


app.UseStatusCodePagesWithReExecute("/error/{0}");

33. Caching


services.AddResponseCaching();
app.UseResponseCaching();

34. Memory Cache


services.AddMemoryCache();

35. Distributed Cache


services.AddDistributedMemoryCache();

36. Session State


services.AddSession();
app.UseSession();

37. Cookie Policy


services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

38. Anti-Forgery Tokens


services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
});

39. HTTPS Redirection


app.UseHttpsRedirection();

40. HSTS (HTTP Strict Transport Security)


app.UseHsts();

41. Content Security Policy


app.UseCsp(options => {
options.DefaultSources(s => s.Self());
});

42. Rate Limiting


services.AddRateLimiter(options => {
options.AddPolicy("RateLimit", policy => {
policy.Limit = 100;
policy.Period = TimeSpan.FromMinutes(1);
});
});

43. Health Checks with Custom Checks


builder.Services.AddHealthChecks()
.AddCheck("MyCustomCheck", () => HealthCheckResult.Healthy());

44. API Documentation with Swagger


app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

45. Using View Components


public class MyViewComponent : ViewComponent {
public IViewComponentResult Invoke() {
return View();
}
}

46. Razor View Engine


@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>

47. Partial Views


@Html.Partial("_MyPartialView", model)

48. Layouts


@{
Layout = "_Layout";
}

49. ViewBag and ViewData


ViewBag.Message = "Hello from ViewBag!";
ViewData["Message"] = "Hello from ViewData!";

50. TempData


TempData["Message"] = "This is a temporary message.";

51. ModelState Validation


if (!ModelState.IsValid) {
return View(model);
}

52. Custom Model Binder


public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}

53. Action Filters


public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}

public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}

54. Result Filters


public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}

public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}

55. Exception Filters


public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}

56. Resource Filters


public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}

public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}

57. Global Filters


services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});

58. Custom Error Pages


app.UseStatusCodePagesWithReExecute("/error/{0}");

59. Caching


services.AddResponseCaching();
app.UseResponseCaching();

60. Memory Cache


services.AddMemoryCache();

61. Distributed Cache


services.AddDistributedMemoryCache();

62. Session State


services.AddSession();
app.UseSession();

63. Cookie Policy


services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

64. Anti-Forgery Tokens


services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
});

65. HTTPS Redirection


app.UseHttpsRedirection();

66. HSTS (HTTP Strict Transport Security)


app.UseHsts();

67. Content Security Policy


app.UseCsp(options => {
options.DefaultSources(s => s.Self());
});

68. Rate Limiting


services.AddRateLimiter(options => {
options.AddPolicy("RateLimit", policy => {
policy.Limit = 100;
policy.Period = TimeSpan.FromMinutes(1);
});
});

69. Health Checks with Custom Checks


builder.Services.AddHealthChecks()
.AddCheck("MyCustomCheck", () => HealthCheckResult.Healthy());

70. API Documentation with Swagger


app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

71. Using View Components

public class MyViewComponent : ViewComponent { public IViewComponentResult Invoke() { return View(); }}

72. Razor View Engine


@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>

73. Partial Views


@Html.Partial("_MyPartialView", model)

74. Layouts


@{
Layout = "_Layout";
}

75. ViewBag and ViewData


ViewBag.Message = "Hello from ViewBag!";
ViewData["Message"] = "Hello from ViewData!";

76. TempData


TempData["Message"] = "This is a temporary message.";

77. ModelState Validation


if (!ModelState.IsValid) {
return View(model);
}

78. Custom Model Binder


public class MyModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
// Custom binding logic
return Task.CompletedTask;
}
}

79. Action Filters


public class MyActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
// Logic before action executes
}

public void OnActionExecuted(ActionExecutedContext context) {
// Logic after action executes
}
}

80. Result Filters


public class MyResultFilter : IResultFilter {
public void OnResultExecuting(ResultExecutingContext context) {
// Logic before result executes
}

public void OnResultExecuted(ResultExecutedContext context) {
// Logic after result executes
}
}

81. Exception Filters


public class MyExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
// Handle exception
}
}

82. Resource Filters


public class MyResourceFilter : IResourceFilter {
public void OnResourceExecuting(ResourceExecutingContext context) {
// Logic before resource executes
}

public void OnResourceExecuted(ResourceExecutedContext context) {
// Logic after resource executes
}
}

83. Global Filters


services.AddControllers(options => {
options.Filters.Add(new MyActionFilter());
});

84. Custom Error Pages


app.UseStatusCodePagesWithReExecute("/error/{0}");

85. Caching


services.AddResponseCaching();
app.UseResponseCaching();

86. Memory Cache


services.AddMemoryCache();

87. Distributed Cache


services.AddDistributedMemoryCache();

88. Session State


services.AddSession();
app.UseSession();

89. Cookie Policy


services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

90. Anti-Forgery Tokens


services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
});

91. HTTPS Redirection


app.UseHttpsRedirection();

92. HSTS (HTTP Strict Transport Security)


app.UseHsts();

93. Content Security Policy


app.UseCsp(options => {
options.DefaultSources(s => s.Self());
});

94. Rate Limiting


services.AddRateLimiter(options => {
options.AddPolicy("RateLimit", policy => {
policy.Limit = 100;
policy.Period = TimeSpan.FromMinutes(1);
});
});

95. Health Checks with Custom Checks


builder.Services.AddHealthChecks()
.AddCheck("MyCustomCheck", () => HealthCheckResult.Healthy());

96. API Documentation with Swagger


app.UseSwagger ();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

97. Using View Components


public class MyViewComponent : ViewComponent {
public IViewComponentResult Invoke() {
return View();
}
}

98. Razor View Engine


@model MyModel
<h1>@Model.Title</h1>
<p>@Model.Description</p>

99. Partial Views


@Html.Partial("_MyPartialView", model)

100. Layouts


@{
Layout = "_Layout";
}