【发布时间】:2020-04-02 07:27:42
【问题描述】:
我是 asp.net 核心的新手,我正在探索对控制器中定义的函数进行 api 调用的不同方法。
我有一个基本的新闻控制器如下,如果我在这个控制器中只保留一个函数GetAll(),那么我可以使用https://localhost:44364/api/news成功调用api
当我添加其他两个函数时,相同的 https://localhost:44364/api/news 会收到如下错误消息,这很明显,因为我没有在我的 url 中提及函数名称。
我的问题是如何为每个函数定义路由,以便我可以通过 url 和 ajax 函数调用这些函数中的每一个
错误
BookListRazor.Controllers.NewsController.GetSingleNews (BookListRazor)
BookListRazor.Controllers.NewsController.GetAll (BookListRazor)
BookListRazor.Controllers.NewsController.GetAllNews (BookListRazor)
代码
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) });
}
}
}
【问题讨论】:
标签: c# asp.net asp.net-core razor-pages