General
Your first ASP.NET App: Controllers
Сабака Чабака DEV Community 周榜
25 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
Semantic tag vs Non-Semantic tag
General
51
Dev.to (EN Zone)
How LinkedIn "Bold" Text Actually Works (It's Not Bold At All)
General
43
Dev.to (EN Zone)
Google ADK Callbacks Are a Policy Plane, Not Just Hooks
General
44
DEV Community 周榜
How I Modelled My Power BI Data — Data Modelling, Relationships & Joins (Kenya Crops Dataset)
General
41
DEV Community 周榜
Comments0
No comments yet — be the first