General
Your first ASP.NET App: Controllers
Сабака Чабака DEV Community 周榜
6 views
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
{
}
Let's set base configuration
using Microsoft.AspNetCore.Mvc;
namespace ExampleProject;
[Route("[controller]")]
[ApiController]
public class MyController : ControllerBase
{
}
Now let's move our endpoint here
remove
app.MapGet("/", () => "Hello World!");
from main file and add
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok("Hello, world!");
}
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();
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.");
}
In next series we learn Databases and more!!!
Read original: https://dev.to/__f5cd865bec2/your-first-aspnet-app-controllers-5ck7
← Previous
Why I built an ad-free Android video player to replace bloated alternatives
Next →
Catching a Silent AWS Failure: A Serverless Daily Report for Suspended Auto Scaling Groups
Related
TACACS+ Failover Testing: Rejection, Outage, and Recovery Are Different Tests
General
0
DEV Community 周榜
Caesar Cipher Explained: How It Works, Encryption, Decryption, and Examples
General
0
DEV Community 周榜
Why I Built My Portfolio with Bun + Astro + MDX Instead of a More Complex Stack
General
0
DEV Community 周榜
Your primary key shouldn't be in the URL
General
0
DEV Community 周榜
Comments0
No comments yet — be the first