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!
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.
public void SayHello(string name)
{
Console.WriteLine("Hello, " + name);
}In the above example, SayHello is a method that prints a personalized greeting.
To use a method, you call it by its name and provide any necessary arguments.
SayHello("John");In this example, SayHello method is called with an argument "John", and it will print "Hello, John" to the console.
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.
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.
To map a method to a route, we use the [Route] attribute.
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.
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! 🎯