简体   繁体   English

Postman 为简单的 ASP.NET Core Web API 收到 404 错误

[英]Postman getting 404 error for simple ASP.NET Core Web API

I have set up a very simple ASP.NET Core 2.1 Web API project, and have created to following simple controller that fetches entites using EF Core.我已经建立了一个非常简单的 ASP.NET Core 2.1 Web API 项目,并创建了以下简单的控制器,该控制器使用 EF Core 获取实体。

The problem is that when trying to access the GetEntities method using Postman, the response is a 404 error.问题是当尝试使用 Postman 访问 GetEntities 方法时,响应是 404 错误。 I used an HTTP GET method on the following URL.我在以下 URL 上使用了 HTTP GET 方法。

https://localhost:44311/api/entities

The response body contains the message <pre>Cannot GET /api/entities</pre> .响应正文包含消息<pre>Cannot GET /api/entities</pre>

Why is Postman receiving a 404 error for this route?为什么 Postman 会收到这条路由的 404 错误?

EntitiesController.cs实体控制器.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);
        }
    }
}

Why is Postman receiving a 404 error for this route?为什么 Postman 会收到这条路由的 404 错误?

The issue was the controller token [controller] was missing from the route template on the controller, causing the route to be hard-coded to api/controller .问题是控制器上的路由模板中缺少控制器令牌[controller] ,导致路由被硬编码为api/controller

That meant that when requesting api/entities it technically did not exist and thus 404 Not Found when requested.这意味着当请求api/entities 时,它在技术上不存在,因此在请求时404 Not Found

Update the route template on the controller.更新控制器上的路由模板。

[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);
    }
}

Reference Routing to controller actions in ASP.NET Core : Token replacement in route templates ([controller], [action], [area]) ASP.NET Core 中控制器动作的参考路由:路由模板中的令牌替换([controller], [action], [area])

Your route is "api/controller", not "api/entities".您的路线是“api/controller”,而不是“api/entities”。 You need to put square brackets around "controller" for the desired effect - "api/[controller]" .您需要将方括号放在 "controller" 周围以获得所需的效果 - "api/[controller]"

确保控制器文件名和类名正确,后缀应带有“Controller”字样,例如,UsersController.cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM