'Is there a way to use one httpget request to handle multiple query string parameters in c#?
I am new to c# and using controllers for that matter. The below code works by querying for a parameter using api/Accounts?mgmId=00u100gp4rDgSjGup1t7
[HttpGet]
public async Task<ActionResult<IEnumerable<Accounts>>> GetAccountDataAsync(string? mgmId)
{
try
{
string query = $"SELECT * FROM c WHERE c.MGMId=@mgmId";
QueryDefinition queryDefinition = new QueryDefinition(query).WithParameter("@mgmId", mgmId);
var account = await _accountService.GetAccountDataAsync(queryDefinition);
return Ok(account);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(404, "Not Found");
}
}
What I would like to do is pass something like the following so I could query by any key, not only mgmId, in a CosmosDb database.
[HttpGet]
public async Task<ActionResult<IEnumerable<Accounts>>> GetAccountDataAsync(Accounts acc)
{
try
{
string query = $"SELECT * FROM c WHERE c.MGMId=@mgmId";
QueryDefinition queryDefinition = new QueryDefinition(query).WithParameter("@mgmId", acc.MGMId);
var account = await _accountService.GetAccountDataAsync(queryDefinition);
return Ok(account);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(404, "Not Found");
}
}
I am putting my Accounts.cs below
public class Accounts
{
[JsonPropertyName("id")]
public string? Id { get; set; }
[JsonPropertyName("MGMId")]
public string MGMId { get; set; } = null!;
[JsonPropertyName("MlifeId")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public long MlifeId { get; set; } = 0!;
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? OperaId {get; set;}
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public object? Profile {get; set;}
}
And this is my AccountsService
public async Task<IEnumerable<Accounts>> GetAccountDataAsync(QueryDefinition queryString)
{
var query = this._container.GetItemQueryIterator<Accounts>(queryString);
List<Accounts> results = new List<Accounts>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
This is the Error I get when trying to pass the Accounts as a parameter by model binding: "errors": { "$": [ "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0." ], "acc": [ "The acc field is required." ]
Solution 1:[1]
Regarding your scenario, you need to add FromQuery attribute to get your data for the GET operation:
[HttpGet]
public async Task<ActionResult<IEnumerable<Accounts>>> GetAccountDataAsync([FromQuery]Accounts acc)
You can read more on parameter binding on MSDN.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul Sharma |
