邮递员在 .net 核心的 api 中返回未找到 404

Postman returning not found 404 in api of .net core

net core 3.1,关于post方法,postman returns状态404未找到。注释的代码是我试过的。

   [Route("api/Servicio")]
    public class ServicioController : Controller
    
            private readonly ApplicationDbContext _context;
    
            public ServicioController(ApplicationDbContext context)
            {
                _context = context;
            }
    
            // POST: api/PostServicio
            //[HttpPost("api/PostServicio")]
            //[HttpPost("servicio")]
            [HttpPost("api/PostServicio/{servicio}")]
            //public async Task<ActionResult<Servicio>> PostServicio([FromBody]Servicio servicio)
            public async Task<ActionResult<Servicio>> PostServicio(Servicio servicio)
            {
                _context.Servicio.Add(servicio);
                await _context.SaveChangesAsync();
                
                return CreatedAtAction(nameof(GetServicio), new { id = servicio.Id }, servicio);
            }

   // GET: api/GetServicio/5        
   [HttpGet("GetServicio/{tecnico}/{semanaDelAno}")]
   public async Task<ActionResult<Servicio>> GetServicio(string tecnico, int semanaDelAno)
   {
            var servicio = await _context.Servicio.FirstOrDefaultAsync(i => i.Tecnico == tecnico && 
              i.SemanaDelAno == semanaDelAno);

            if (servicio == null)
            {
                return NotFound();
            }

            return servicio;
   }

}

在 postman 我有一个 body, raw, json

{
  "Tecnico":"Jhon",
  "ServicioRealizado":"Servicio1",
  "SemanaDelAno": 1,
  "Dia": "Lunes",
  "HoraInicial": 13.0,
  "HoraFinal": 15.0
}

我有这两个动作,这段代码基本上是从文档中的 api 教程中得到的。

更新 ******************************************** ****

  // POST: api/PostServicio        
        [HttpPost("PostServicio")]        
        public async Task<ActionResult<Servicio>> PostServicio([FromBody]Servicio servicio)        
        {
            _context.Servicio.Add(servicio);
            await _context.SaveChangesAsync();

            //return CreatedAtAction(nameof(GetServicio), new { tecnico = servicio.Tecnico }, new { semanaDelAno = servicio.SemanaDelAno });
            return servicio;
        }

现在可以了

确保您的请求 url 是:https://localhost:portNumber/api/Servicio/api/PostServicio/xxx.xxx 匹配 {servicio}.

但实际上我认为不需要将 {servicio} 添加到您的 HttpGet attribute.Because 您 post 来自正文的数据而不是 route.So {servicio} 这里是 useless.Just 使用 [HttpPost("api/PostServicio")] 和请求 url:https://localhost:portNumber/api/Servicio/api/PostServicio。然后 post 来自主体的数据通过选择原始 json在 postman.

参考:

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#attribute-routing-with-http-verb-attributes