.NET 7 Preview 3 is out and in this post let's see how we can customize Controller Action parameter binding using TryParse in Minimal APIs.
Let's consider the following code.
// /employees/search?searchCriteria={"name":"John"} app.MapGet("/employees/search", async (EmployeeContext dbContext, EmployeeSearchCriteria searchCriteria, CancellationToken cancellationToken) => { return await dbContext.Employees .Where(x => x.Name == searchCriteria.Name) .ToListAsync(cancellationToken); }) .Produces<List<Employee>>(StatusCodes.Status200OK); public class EmployeeSearchCriteria { public string Name { get; set; } }
Here let's say, I want to bind the query parameter searchCriteria that I am sending to the searchCriteria object in the action. Here above code won't work, because the runtime has no knowledge of translating the query parameter to the searchCriteria object. We can instruct the runtime on how it should get translated by using TryParse.
I am updating the EmployeeSearchCriteria class by introducing the following TryParse method.
public class EmployeeSearchCriteria { public string Name { get; set; } public static bool TryParse(string value, out EmployeeSearchCriteria result) { if (value is null) { result = default; return false; } JsonSerializerOptions options = new() { PropertyNameCaseInsensitive = true }; result = JsonSerializer.Deserialize<EmployeeSearchCriteria>(value, options); return true; } }
ASP.NET Core will look for a TryParse method in a complex object parameter when trying to do the parameter binding. The TryPrase method signature should be one of the following.
public static bool TryParse(string value, T out result); public static bool TryParse(string value, IFormatProvider provider, T out result);
Now moving back to the code sample, if I run the updated code, I can see the query parameter searchCriteria is correctly bound to the object.
Customize Action Parameter Binding using TryParse |
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment