I have structs which represents Id's for different types. That structs have int property "Id", public constructor with (int id) parameter and implements IEquatable interface. I want my ASP.Net Core WebAPI application to somehow bind those structs to incoming integer Ids in query. I know that there are custom model binders, but to use it I need to implement custom model binders for all query models, because marking each key-struct property with custom model binder not enough - I need to register custom model binder provider, where I switch ModelType and return single model binder, like so:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(DogQueryModel))
{
return new BinderTypeModelBinder(typeof(DogQueryModelBinder));
}
So I can't create just one model binder for each Id struct - need to create it for each query model.
To make it clear I will provide some example code of that struct, query model and action:
public struct DogKey : IEquatable<DogKey>
{
public DogKey(int id)
{
Id = id;
}
public int Id { get; }
#region IEquatable implementation
#endregion IEquatable implementation
}
public class DogQueryModel
{
public DogKey Id { get; set; }
public SomeOtherKey OtherId { get; set; }
public string Name { get; set; }
}
[HttpGet("dog")]
public async Task<ActionResult<IList<DogResultModel>>> GetDogs([FromQuery]DogQueryModel dogQueryModel)
{
//use dogQueryModel.Id as DogKey struct
}
I want to query it like this: https://localhost/api/v1/dogs/dog?id=1&otherId=2&Name=dogname
Aucun commentaire:
Enregistrer un commentaire