Home > Mobile >  Remove nested complex-type's property name from displayed query parameter name, only show child
Remove nested complex-type's property name from displayed query parameter name, only show child

Time:01-04

My controller contains this code:

[HttpGet]
public IActionResult GetNewQuestLocation([FromQuery]UserLocationPreferences userLocationPrefs)
{
    //code here
}

Here is the model used as the parameter:

public record UserLocationPreferences(Location UserLoc, UserSettingsDto UserSettings);

And its child parameters:

public record Location(double Latitude, double Longitude);
public record UserSettingsDto(double MaxDistance, double MinDistance);

Problem

I have minimal experience creating API's and I have ran into an issue where a complex-type within another complex-type shows the complex-type's property name in the parameter name of the query.
For instance, on Swagger this is how the above endpoint looks: Endpoint above shown on Swagger

and its full URL looks like this:

https://exampleAPI.com/api/quest?UserLoc.Latitude=53.74&UserLoc.Longitude=-2.498&UserPrefs.MaxDistance=1.0&UserPrefs.MinDistance=0.5

I wish to remove the UserLoc and UserSettings in this endpoint by way of aliasing the parameter such that it does not contain the complex-type's property name, just the primitive within the type:

UserLoc.Latitude -> Latitude

UserSettings.MinDistance -> MinDistance etc.

I believe it is something to do with model binding but i am new to that and I haven't found a resouce online that tackles this type of scenario.
If this is a bad idea, please let me know why. My reason for doing this is because I found the query a little long and it would be an issue if multiple nested types later down the line would extend the query size dramatically. My thought was to alias these parameters for ease of use.

Thanks in advance!

CodePudding user response:

Here is a workaround to use model class instead of record:

public class Location
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}
public class UserSettingsDto
{
    public double MaxDistance { get; set; }
    public double MinDistance { get; set; }
}

Controller:

    [Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult GetNewQuestLocation([FromQuery] Location UserLoc, [FromQuery] UserSettingsDto UserSettings)
    {
        return Ok();
    }
}

Result:

enter image description here

My thought was to alias these parameters for ease of use.

If you must use record, you can change the parameter name like below to reduce the query string length:

public record UserLocationPreferences(Location l,  UserSettingsDto u);

Result:

enter image description here

  •  Tags:  
  • Related