Description
Is there an existing issue for this?
- I have searched the existing issues
Is your feature request related to a problem? Please describe the problem.
I would like to pass an object (instead of primitive type) as a parameter to my minimal API as part of a get request.
Basically, I have a Bazlor component that runs on the client (using InteractiveWebassembly render mode) which invokes a minimal api end point on the server in the following way:
GetFromJsonAsync
Example:
I have the following minimal API code:
builder.MapGet("/api/counties", GetCounties2);
Task<IList<CodeType>> GetCounties2(string keywords, [FromQuery] AutoCompleteParameters parameters, ICountiesService countiesService, HttpContext context)
Invocation from the WebAssembly component:
` public async Task<IList> GetCountiesAsync(string keywords, AutoCompleteParameters parameters)
{
var qs = $"?keywords={keywords}";
qs = parameters.AppendToQuery(qs);
Console.WriteLine(qs);
var coll = await _http.GetFromJsonAsync<CodeType[]>($"/api/counties/{qs}") ?? [];
return coll;
} `
The AppendToQuery() method is (which just appends key/value pair to query string for each public field that is set by the user):
var buff = new StringBuilder(queryString); var fields = this.GetType().GetFields(); foreach (var field in fields) { var value = field.GetValue(this); if (value != null) { buff.Append($"&{field.Name}={value}"); } } return buff.ToString();
I have followed instructions at (https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api) and tried the first 2 examples, using FromQuery and Type Converters, and both examples did not work. I haven't tried the 3rd example using a "Model Binder" example since I don't know if that will work either.
When using the FromQuery attribute I got an exception that my type did not have TryParse() method. After adding TryParse() method, it was never called by the run time.
As for the type converter, I added it to my type and it was completely ignored. I keep getting null for the parameter on the server for my object, the type converter is not used and my TryParse is not being invoked.
[TypeConverter(typeof(AutoCompleteParametersConverter))] public class AutoCompleteParameters
Implementation of my type converter is:
`internal class AutoCompleteParametersConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string)
{
AutoCompleteParameters p;
if (AutoCompleteParameters.TryParse((string)value, out p))
{
return p;
}
}
return base.ConvertFrom(context, culture, value);
}
}`
Describe the solution you'd like
See original problem description.
Additional context
No response