'AspNet Core Controller GET Request using multiple variables
I am trying to build an webapi route that will allow me to query more than 1 parameter on the objects at a time, without having to use result filtering.
Say I have a class called AppxPackage, and I want to search for all results that contain more than 1 parameter, in this case WinRelease and WinVersion, how do I get the results containing both?
Below is my code that I tried, it compiles, but always returns a 404 even when the results do exist.
AppxPackage.cs
public class AppxPackage
{
public int Id { get; set; }
public string Name { get; set; }
public string[] WinRelease { get; set; }
public string[] WinEdition { get; set; }
public string[] WinVersion { get; set; }
}
[HttpGet("winversion/{winversion}/winrelease/{winrelease}")]
public async Task<ActionResult<IEnumerable<AppxPackage>>> GetAppxPackageByWinVersion([FromRoute]string winversion, [FromRoute]string winrelease)
{
var packages = _context.AppxPackages.Where(
a => a.WinVersion.Contains(winversion)
.WinEdition.Contains(winrelease));
if (packages.Count() == 0)
{
return NotFound();
}
return await packages.ToListAsync();
}
I have already tried a variation of the search like this too:
var packages = _context.AppxPackages.Where(a => a.WinVersion.Contains(winversion)).Where(a => a.WinEdition.Contains(winedition));
Both unsuccessful. Do I need to index against the returned result packages instead somehow?
Solution 1:[1]
Thanks for Keith for his comment - I was able to amend the code and got it working:
[HttpGet("winversion/{winversion}/winrelease/{winrelease}")]
public async Task<ActionResult<IEnumerable<AppxPackage>>> GetAppxPackageByWinVersion([FromRoute]string winversion, [FromRoute]string winrelease)
{
var packages = _context.AppxPackages.Where(
a => a.WinVersion.Contains(winversion) &&
a.WinEdition.Contains(winrelease));
if (packages.Count() == 0)
{
return NotFound();
}
return await packages.ToListAsync();
}
I was not using the correct syntax, and now this is operating exactly how I intended it to work. Thank you for your support!
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 | danijeljw-RPC |
