【问题标题】:Postman getting 404 error for simple ASP.NET Core Web APIPostman 收到简单的 ASP.NET Core Web API 的 404 错误
【发布时间】:2018-12-29 20:27:28
【问题描述】:

我已经建立了一个非常简单的 ASP.NET Core 2.1 Web API 项目,并创建了一个使用 EF Core 获取实体的简单控制器。

问题是当尝试使用 Postman 访问 GetEntities 方法时,响应是 404 错误。我在以下 URL 上使用了 HTTP GET 方法。

https://localhost:44311/api/entities

响应正文包含消息<pre>Cannot GET /api/entities</pre>

为什么 Postman 收到此路由的 404 错误?

EntitiesController.cs

namespace MyProject.Controllers
{
    [Route("api/controller")]
    public class EntitiesController : Controller
    {
        private readonly ApplicationDbContext dbContext;

        public EntitiesController(ApplicationDbContext _dbContext)
        {
            this.dbContext = _dbContext;
        }

        [HttpGet]
        public IActionResult GetEntities()
        {
            var result = dbContext.Entities.ToListAsync();
            return Ok(result);
        }
    }
}

【问题讨论】:

    标签: c# http asp.net-core postman


    【解决方案1】:

    确保控制器文件名和类名正确,后缀为“Controller”,如UsersController.cs

    【讨论】:

      【解决方案2】:

      您的路线是“api/controller”,而不是“api/entities”。您需要在“控制器”周围加上方括号以获得所需的效果 - "api/[controller]"

      【讨论】:

        【解决方案3】:

        为什么 Postman 收到此路由的 404 错误?

        问题是控制器上的路由模板中缺少控制器令牌[controller],导致路由被硬编码为api/controller

        这意味着在请求 api/entities 时,它在技术上并不存在,因此在请求时 404 Not Found

        更新控制器上的路由模板。

        [Route("api/[controller]")]
        public class EntitiesController : Controller {
            private readonly ApplicationDbContext dbContext;
        
            public EntitiesController(ApplicationDbContext _dbContext) {
                this.dbContext = _dbContext;
            }
        
            //GET api/entities
            [HttpGet]
            public async Task<IActionResult> GetEntities() {
                var result = await dbContext.Entities.ToListAsync();
                return Ok(result);
            }
        }
        

        参考Routing to controller actions in ASP.NET Core : Token replacement in route templates ([controller], [action], [area])

        【讨论】:

          猜你喜欢
          • 2019-11-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-27
          • 2017-12-04
          • 1970-01-01
          • 1970-01-01
          • 2013-10-01
          相关资源
          最近更新 更多