Implementing MapQuery For ASP.NET in C# & .NET
[C#, ASP.NET, .NET]
In a previous post, “Creating A Web API Method That Supports QUERY in C# & .NET”, we looked at how to add HTTP QUERY support to an ASP.NET web API.
We also noted that 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.
In this post, we shall implement that.
As a reminder our payload looks like this:
{
"SearchText": "conrad",
"SortColumn": "Name",
"PageNumber": 0,
"PageSize": 20,
"Database": "Animals",
"ActiveOnly": true
}
Which maps to an object like this:
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; }
}
Our endpoint looked like this:
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();
It is going to be tedious having to repetitively manually add support in this fashion.
To work around this, we write an extension method for MapQuery.
It looks like this:
public static class QueryEndpointExtensions
{
public static RouteHandlerBuilder
MapQuery(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler) =>
endpoints.MapMethods(pattern, [HttpMethods.Query], handler);
}
This allows us to rewrite our endpoint like this:
app.MapQuery("/",
(SearchRequest request, ILogger<Program> logger) =>
{
logger.LogDebug("Executing search query {@Query}", request);
logger.LogInformation("Searching for {Search}", request.SearchText);
return TypedResults.Ok(request);
});
Here we can see that MapQuery has neatly abstracted for us the implementation.
Our API still works as expected:

And returns what we expect:

TLDR
We can develop our own MapQuery method to implement the missing extension.
The code is in my GitHub.
Happy hacking!