Reputation: 15239
I have the following controller (.NET Core Web API application)
(Source
contains multiple Site
's)
SitesController.cs
// GET: api/sites
[HttpGet]
public IDictionary<int, Site> GetSites() {
return _db.Sites.ToDictionary(s => s.SiteId, s => s);
}
// GET: api/sites?source=5
[HttpGet("{source}")]
public IDictionary<int, Site> GetSites([FromRoute] int source) {
return _db.Sites.Where(s => s.SourceId == source).ToDictionary(s => s.SiteId, s => s);
}
// GET: api/sites/5
[HttpGet("{id}")]
public async Task<IActionResult> GetSite([FromRoute] int id) {
When the Angular client asks Site
s only from a Source
, I however get all the sites, the function with the int source
param is not called... Why?
findAllSourceSites(sourceId: number): Observable<Site[]> {
return this.http.get(`${this.API_URL}/api/sites`, {
params: new HttpParams()
.set('source', sourceId.toString())
}).pipe(
map(res => {
return Object.values(res);
})
);
}
Upvotes: 0
Views: 790
Reputation: 5470
Pretty sure it's because of [FromRoute]
for that to work your URL should be /api/sites/1
, HttpParams
is setting the query string which now your URL looks like /api/sites?source=1
If you want to use query string you should change your controller to [FromQuery]
EDIT:
Due to AmbiguousActionException: Multiple actions matched.
alternative solution would combine both together.
[HttpGet]
public IDictionary<int, Site> GetSites([FromQuery] int? source) {
if (source.HasValue) {
// get specific
} else {
// get all
}
}
Upvotes: 4