gpt4 book ai didi

c# - 如何在asp.net core razor pages项目中调用 Controller 中定义的函数

转载 作者:行者123 更新时间:2023-12-04 10:18:17 27 4
gpt4 key购买 nike

我是 asp.net core 的新手,我正在探索不同的方法来对 Controller 中定义的函数进行 api 调用。

我有一个基本的新闻 Controller ,如下所示,如果我在这个 Controller 中只保留一个功能 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) });
}

}
}

最佳答案

你可以像下面这样改变:

[Route("api/News/[action]")]
[ApiController]

请求网址如下:
//https://localhost:44364/api/news/GetAllNews?langID=1
[HttpGet]
public async Task<IActionResult> GetAllNews(int langID)
{
}

//https://localhost:44364/api/news/GetAll
[HttpGet]
public async Task<IActionResult> GetAll()
{
}

//https://localhost:44364/api/news/GetSingleNews?id=1
[HttpGet]
public async Task<IActionResult> GetSingleNews(int id)
{
}

关于c# - 如何在asp.net core razor pages项目中调用 Controller 中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60986289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com