ASP .NET Tutorial: Use, Run, Map Methods 🎯

beginner
14 min

ASP .NET Tutorial: Use, Run, Map Methods 🎯

Welcome to CodeYourCraft's comprehensive guide on ASP .NET! In this lesson, we'll dive into using, running, and mapping methods. Let's get started!

Understanding Methods 📝

In programming, a method is a series of instructions that perform a specific task. In ASP .NET, methods are used extensively to handle web requests and responses.

Example Method in C# 💡

csharp
public void SayHello(string name) { Console.WriteLine("Hello, " + name); }

In the above example, SayHello is a method that prints a personalized greeting.

Using Methods 💡

To use a method, you call it by its name and provide any necessary arguments.

Calling Method Example 💡

csharp
SayHello("John");

In this example, SayHello method is called with an argument "John", and it will print "Hello, John" to the console.

Running Methods in ASP .NET 💡

When working with ASP .NET, methods are usually associated with HTTP requests and responses. To run a method, we create a controller and map the method to specific routes.

Creating a Simple Controller 💡

csharp
using Microsoft.AspNetCore.Mvc; namespace MyApp.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public string Greet(string name) { return "Hello, " + name; } } }

In the above example, we've created a HomeController with two methods: Index and Greet. The Index method returns a view, while the Greet method returns a string.

Mapping Methods to Routes 💡

To map a method to a route, we use the [Route] attribute.

csharp
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; [Route("api/[controller]")] [ApiController] public class HomeController : ControllerBase { [HttpGet("greet")] public string Greet(string name) { return "Hello, " + name; } }

In the above example, we've added the [Route] and [ApiController] attributes to our HomeController. We've also added the [HttpGet("greet")] attribute to the Greet method, which means this method will be triggered when we make a GET request to /api/home/greet.

Quiz 💡

Quick Quiz
Question 1 of 1

Which attribute is used to map a method to a route in ASP .NET?

That's it for this lesson! In the next lesson, we'll dive deeper into handling HTTP requests and responses in ASP .NET. Stay tuned! 🎯