【发布时间】:2023-03-17 05:14:02
【问题描述】:
我有一个名为“OdeToFood”的小型 ASP.NET Core Web 应用程序项目。开发环境包括:
- IDE:Windows 10 PC 上的 Visual Studio 2019
- ASP.NET Core 3.1
- 使用 Dapper 从 SQL DB 访问数据
- 不使用 MVC
在其中一个网页中,将使用 jQuery .ajax 从 DB 中检索记录。我添加了一个类型为“具有读/写操作的 API 控制器”的 ApiController,因为此项目中未使用 EF。
这是VS自动生成的代码(没有做任何改动)。
namespace OdeToFood.Api
{
[Route("api/[controller]")]
[ApiController]
public class RestaurantsController : ControllerBase
{
// GET: api/<RestaurantsController>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<RestaurantsController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<RestaurantsController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<RestaurantsController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<RestaurantsController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
我尝试使用以下 URL 从浏览器中对其进行测试:
- https://localhost:44361/api/Restaurants
- https://localhost:44361/api/Restaurants/8
- https://localhost:44361/api/RestaurantsController
- https://localhost:44361/api/RestaurantsController/8
它们都因 HTTP 404 错误而失败。
由于上面的代码已经使用 [Route ...] 的“属性路由”,我认为前 2 个 URL 的 int 测试应该可以工作。但他们没有。我不知道为什么。任何帮助或建议将不胜感激。
在 startup.cs 文件中,configure 部分有以下设置:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
【问题讨论】:
标签: c# asp.net-core url-routing asp.net-apicontroller