When the line getJSON is executed and there is routing to for example: https://localhost:44338/ArticleApi/GetNextArticles?id=12&quantity=2&filterName=Odziez
I get error:
Failed to load resource: the server responded with a status of 404 ()
Cannot find this page on localhost
GetNextArticles method in my ArticleApiController:
[HttpGet("{id}/{count}/{filterName}")]
public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
{
return _articleRepository.GetNextArticles(id, count, filterName);
}
in my view (.cshtml file):
$.getJSON('@Url.Action("GetNextArticles", "ArticleApi")' + "?id=" + last + "&quantity=" + quantity + "&filterName=" + filterCategory, function(data, status) {
for(var index in data) {etc...}}
GetNextArticles method:
public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
{
List<Article> articles = new List<Article>();
var categoryId = _context.Categories.Where(c => c.CategoryName == filterName).Select(c => c.CategoryId).FirstOrDefault();
for (int i = 0; i < count; i++)
{
var foundArticles = _context.Articles.Where(a => a.CategoryId == categoryId && a.ArticleId == id + i + 1).ToList();
if (foundArticles.Count() == 0)
{
return articles;
}
var article = foundArticles[0];
if (article != null)
{
article.Category = _context.Categories.Find(article.CategoryId);
articles.Add(article);
}
else
{
var nextArticles = _context.Articles.Where(a => a.CategoryId == categoryId && article.ArticleId <= id + i + 100).ToList();
if (nextArticles.Count != 0)
{
id = nextArticles.Min(a => a.ArticleId);
articles.Add(nextArticles.Where(a => a.ArticleId == id).First());
}
else
{
break;
}
}
}
return articles;
}
2
Answers
According to the error, you could validate the names of the parameters that you are sending. Reviewing the code I realize that one of them is sent with the name "quantity" and in the controller you call it "count"
If you use
[HttpGet("{id}/{count}/{filterName}")]
in your Api, The Url passed into this api must behttps://localhost:44338/ArticleApi/GetNextArticles/Id/count/filterName
.So, If you don’t want to change the
$.getJSON(..){...}
in the View, You can change the api like:You can see the Api works fine and it can be loaded in Swagger as well