I am new to asp.net core and i am exploring different ways to make api calls to function defined in controller.
I have a basic news controller as below, if i keep only one function in this controller GetAll() then i am able to make successful call to api using https://localhost:44364/api/news
and when i add other two function then same https://localhost:44364/api/news gets error message as below which is quite obvious as i am not making not mentioning function name in my url.
My question is how can i define route for each function so that i can call each of these function by url and from ajax function
Error
BookListRazor.Controllers.NewsController.GetSingleNews (BookListRazor)
BookListRazor.Controllers.NewsController.GetAll (BookListRazor)
BookListRazor.Controllers.NewsController.GetAllNews (BookListRazor)
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookListRazor.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BookListRazor.Controllers
{
[Route("api/News")]
[ApiController]
public class NewsController : Controller
{
private readonly ApplicationDbContext _db;
public NewsController(ApplicationDbContext db)
{
_db = db;
}
//get all news by languageID
[HttpGet]
// [Route("api/news/getallnews/{1}")]
public async Task<IActionResult> GetAllNews(int langID)
{
//var query = await _db.News.OrderByDescending(x => x.NewsDate).Where(x => x.LanguageID == 1 && x.NewsActive==true && x.NewsVisible==true).ToListAsync();
return Json(new { data = await _db.News.OrderByDescending(x => x.NewsDate).Where(x => x.LanguageID == langID && x.NewsActive == true && x.NewsVisible == true).ToListAsync() });
}
//get all news
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Json(new { data = await _db.News.OrderByDescending(x => x.NewsDate).Where(x => x.LanguageID == 1 && x.NewsActive == true && x.NewsVisible == true).ToListAsync() });
}
//get single news by newsID
[HttpGet]
public async Task<IActionResult> GetSingleNews(int id)
{
return Json(new { data = await _db.News.FirstOrDefaultAsync(x=>x.NewsID == id) });
}
}
}