Creating A Web API Method That Supports QUERY In C# & .NET
[C#, .NET, ASP.NET]
In a previous post, “What Problem Does HTTP QUERY Solve?”, we discussed the HTTP QUERY method, and how it makes a whole class of APIs and applications easier to design and build.
In today’s post, we will look at how to implement one in practice using ASP.NET Minimal API.
For this we will use the example from an earlier post, “How To Encode An Object For Passing In A URL In C# & .NET”, that has this payload:
{
"SearchText": "conrad",
"SortColumn": "Name",
"PageNumber": 0,
"PageSize": 20,
"Database": "Animals",
"ActiveOnly": true
}
Which we map to this class:
public sealed class SearchRequest
{
public required string SearchText { get; init; }
public required string SortColumn { get; init; }
public required int PageNumber { get; init; }
public required int PageSize { get; init; }
public required string Database { get; init; }
public required bool ActiveOnly { get; init; }
}
We start by generating an empty API project.
dotnet new web -o QueryAPI
The code is as follows:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapMethods("/", [HttpMethods.Query],
(SearchRequest request) =>
{
var response =
$"You requested {request.SearchText} from database {request.Database} sorted by {request.SortColumn}";
return response;
});
app.Run();
Unlike the other well known methods, GET, POST, PUT, DELETE, PATCH there are no ASP.NET equivalents (MapGet, MapPost, MapPut, MapDelete, MapPatch) for QUERY. At least not yet.
We therefore have to use the generic MapMethods and specify our method directly.
app.MapMethods("/", [HttpMethods.Query],
(SearchRequest request) =>
{
// Our logic here
}
The logic itself is pretty standard. Ideally within we would do whatever database access that was required, or fetching from an application level cache.
We can then try this out with an API client.
As usual, Yaak is my goto:

Here we can see that our query has been successfully submitted and responded to.
The raw request is as follows:

For obvious reasons, a body is mandatory.
TLDR
ASP.NET supports building of API and Web endpoints supporting HTTP QUERY
The code is in my GitHub.
Happy hacking!