ASP .NET Core MVC JQuery AJAX - 使用 ajax 通过控制器 api 查看数据时出现问题

ASP .NET Core MVC JQuery AJAX - problem with getting data to view via controller api using ajax

当执行 getJSON 行并且有路由到例如:https://localhost:44338/ArticleApi/GetNextArticles?id=12&quantity=2&filterName=Odziez

我收到错误:

Failed to load resource: the server responded with a status of 404 ()

在本地主机上找不到此页面

我的 ArticleApiController 中的 GetNextArticles 方法:

 [HttpGet("{id}/{count}/{filterName}")]
    public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
    {
        return _articleRepository.GetNextArticles(id, count, filterName);
    }

在我看来(.cshtml 文件):

 $.getJSON('@Url.Action("GetNextArticles", "ArticleApi")' + "?id=" + last + "&quantity=" + quantity + "&filterName=" + filterCategory, function(data, status) {
     
                    for(var index in data) {etc...}}

GetNextArticles 方法:

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;
    }

根据错误,您可以验证您发送的参数的名称。查看代码,我意识到其中一个以名称“quantity”发送,在控制器中你称之为“count”

如果您在 Api 中使用 [HttpGet("{id}/{count}/{filterName}")],则传递给此 api 的 Url 必须是 https://localhost:44338/ArticleApi/GetNextArticles/Id/count/filterName

所以,如果您不想更改视图中的 $.getJSON(..){...},您可以像这样更改 api:

    [HttpGet]
    public IEnumerable<Article> GetNextArticles([FromQuery]int id, int count, string filterName)
    {
        return _articleRepository.GetNextArticles(id, count, filterName);
    }

你可以看到 Api 工作正常,它也可以在 Swagger 中加载