Create a Minimal WebApi Project
First of all create a minimal web api project so that we can focus on this specific item. The completed project can be downloaded from the downloads attached to this video. Open the solution explorer and locate the program.cs file. Double-click to open this file.
As you can see we have a namespace directive for Microsoft.AspNetCore.Mvc - this directive resolves the FromQuery attribute that we have to use for decorating a parameter.
using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(); builder.Services.AddRazorPages(); var app = builder.Build(); // route /{id}?m= app.MapGet("/{id}", (int id, [FromQuery(Name ="m")] String msg) => { String qs = $"QueryString = {msg}"; return Results.Ok(qs); }); app.MapRazorPages(); app.Run();
This is the GET web api that has two parameters - id and msg. The first parameter, id, is implicitly bound to the route parameter called id. We could have decorated it explicitly by using the [FromRoute] attribute also. But it is not necessary because of aspnet core defaults.
app.MapGet( "/{id}", ( [FromRoute] int id, [FromQuery(Name ="m")] String msg ) => { // ... code }
The next parameter has been decorated as [FromQuery] - which means that it is derived from a query string variable called m. The handler receives it through an identifier called msg. We can see that we have two different names for the same data. The name m is for the end-user world, whereas the name msg is for the readability of your program.
The handler for this api echoes back the parameter.
Video Explanation (see it happen!)
Please watch the following youtube video:
Run the Project
Run the project and type a GET request with a url containing a query string parameter m of value equal to 5: https://localhost/34?m=5
We observe that the result succeeds and our querystring variable is echoed back without errors.
Let us experiment a little bit now! Remove the query string so that we are not sending any data for m.
Send the GET request - and we observe that an exception is thrown now.
It happens because the binding of the query string has failed - there was no variable called m!
Let us now mark m as optional by changing String to String?, so that it becomes nullable and, hence, an optional parameter.
// msg has been marked optional, nullable app.MapGet( "/{id}", ( [FromRoute] int id, [FromQuery(Name ="m")] String? msg ) => { // ... code }
We can run the project again and verify that the api call succeeds without error.
This is how we can bind a parameter to a query-string source. Thanks!
This Blog Post/Article "(C# ASP.NET Core) [FromQuery] Parameter Binding of a QueryString Variable" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.