DEV Community

Cover image for Your first ASP.NET App: Controllers
Сабака Чабака
Сабака Чабака

Posted on

Your first ASP.NET App: Controllers

Hello! In this tutorial we continue build your own ASP.NET Service!

Requirements

  • IDE like Visual Studio/JetBrains Rider
  • .NET >= 10
  • Base C# skill

Creating controller

Lets create our Controller, create file "MyController.cs"
Image will like this

namespace ExampleProject;

public class MyController
{

}
Enter fullscreen mode Exit fullscreen mode

Let's set base configuration

using Microsoft.AspNetCore.Mvc;

namespace ExampleProject;

[Route("[controller]")]
[ApiController]
public class MyController : ControllerBase
{

}
Enter fullscreen mode Exit fullscreen mode

Now let's move our endpoint here
remove

app.MapGet("/", () => "Hello World!");
Enter fullscreen mode Exit fullscreen mode

from main file and add

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        return Ok("Hello, world!");
    }
Enter fullscreen mode Exit fullscreen mode

to our controller

Now we need to add this controller to Program.cs

using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();
builder.Services.AddControllers();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

app.MapControllers();

app.Run();
Enter fullscreen mode Exit fullscreen mode

Now let's run!

Open scalar at localhost:[your port]/scalar

press "Test Request" and press "Run"

And now we received "Hello, world!" from our controller

We can add more endpoints
like this

    [HttpGet("{name}")]
    public async Task<IActionResult> Get(string name)
    {
        var start = DateTime.Now;
        await Task.Delay(1000);
        var end = DateTime.Now;
        return Ok($"Hello, {name}! It took {end - start} to respond.");
    }
Enter fullscreen mode Exit fullscreen mode

In next series we learn Databases and more!!!

Top comments (0)