ZetCode

ASP.NET MapGet

last modified September 28, 2022

In this article we show how to map GET requests to handlers in ASP.NET.

ASP.NET is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, web applications. It is developed by Microsoft.

The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

GET requests:

The MapGet method adds a RouteEndpoint to the endpoint builder that matches HTTP GET requests for the specified pattern.

ASP.NET MapGet example

The following is a simple MapGet example.

Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "home page\n");
app.MapGet("/about", () => "about page\n");

app.Run("http://localhost:3000");

We map two endpoints with MapGet.

app.MapGet("/", () => "home page\n");

With MapGet, we map the lambda expression to the / path.

app.Run("http://localhost:3000");

The application listens on port 3000.

$ curl localhost:3000
home page
$ curl localhost:3000/about
about page

We generate two GET requests.

$ curl localhost:3000 -X POST -i
HTTP/1.1 405 Method Not Allowed
Content-Length: 0
Date: Wed, 28 Sep 2022 11:33:34 GMT
Server: Kestrel
Allow: GET

$ curl localhost:3000/about -X POST -i
HTTP/1.1 405 Method Not Allowed
Content-Length: 0
Date: Wed, 28 Sep 2022 11:33:39 GMT
Server: Kestrel
Allow: GET

However, the POST requests are not allowed.

ASP.NET MapGet example II

In the next example, we map two endpoints to local functions.

Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", homePage);
app.MapGet("/about", aboutPage);

app.Run("http://localhost:3000");

string homePage() => "home page\n";
string aboutPage() => "about page\n";

We have two endpoints.

app.MapGet("/", homePage);
app.MapGet("/about", aboutPage);

We map the two endpoints to two local functions.

Program.cs
using var client = new HttpClient();
var content = await client.GetStringAsync("http://localhost:3000/about");

Console.WriteLine(content);

We create a C# console application which sends a GET request to one of the endpoints. We use the HttpClient class.

$ dotnet run 
about page

We run the console application and receive a response from the ASP.NET application.

In this article, we have shown how to map GET requests with MapGet in ASP.NET.