Friday, April 15, 2022

ASP.NET Core: Custom Controller Action Parameter Binding using TryParse in Minimal APIs

.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"}
    async (EmployeeContext dbContext,
        EmployeeSearchCriteria searchCriteria,
        CancellationToken cancellationToken) =>
    return await dbContext.Employees
        .Where(x => x.Name == searchCriteria.Name)
public class EmployeeSearchCriteria
    public string Name getset; }

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 objectWe 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 { getset; }
    public static bool TryParse(string valueout 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
Hope this helps.

Happy Coding.


No comments:

Post a Comment