【问题标题】:Why is the route in apicontroller not working?为什么 apicontroller 中的路由不起作用?
【发布时间】:2020-05-06 21:18:28
【问题描述】:

我有一个名为“GebruikersController”的控制器类

当我使用“https://localhost:5001/Gebruikers”时,我得到了正确的输出,但是当我使用“https://localhost:5001/api/GebruikerController/Gebruikers”时(它应该如何工作?)我得到一个空白页。有谁能够帮我?谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RESTAPI.Data;
using RESTAPI.Data.Repositories;
using RESTAPI.DTOs;
using RESTAPI.Models;

namespace RESTAPI.Controllers
{
  [ApiConventionType(typeof(DefaultApiConventions))]
  [Produces("application/json")]
  [Route("api/[controller]")]
  [ApiController]
  public class GebruikersController : ControllerBase
  {
    private readonly IGebruikerRepository _gebruikerRepository;

    public GebruikersController(IGebruikerRepository context)
    {
            _gebruikerRepository = context;
    }

    // GET: api/Gebruikers
    /// <summary>
    /// Geeft alle gebruikers geordend op achternaam
    /// </summary>
    /// <returns>array van gebruikers</returns>
    [HttpGet("/Gebruikers")]
    public IEnumerable<Gebruiker> GetGebruikers()
    {
            return _gebruikerRepository.GetAlleGebruikers().OrderBy(d => d.Achternaam);
    }

    // GET: api/Gebruikers/5
    /// <summary>
    /// Geeft de gebruiker met het gegeven id terug
    /// </summary>
    /// <param name="id">het id van de gebruiker</param>
    /// <returns>De gebruiker</returns>
    [HttpGet("{id}")]
    public ActionResult<Gebruiker> GetGebruiker(int id)
    {
      Gebruiker gebruiker = _gebruikerRepository.GetBy(id);
      if (gebruiker == null) return NotFound();
      return gebruiker;
    }

  }
}

【问题讨论】:

    标签: c# asp.net-core controller


    【解决方案1】:

    尝试使用 https://localhost:5001/api/Gebruikers/Gebruikers 代替 https://localhost:5001/api/GebruikerController/Gebruikers.

    controller”字没有写在 URL 中。

    【讨论】:

    • 当我使用那个我得到一个错误。 {"type":"tools.ietf.org/html/... 或出现更多验证错误。","status":400,"traceId":"|50c831bb-4dab87ead88f6d56.","errors":{"id": ["'Gebruikers' 的值无效。"]}}
    • 其实Controller的名字是带s的GebruikersController,localhost:5001/api/Gebruikers/Gebruikers你怎么办?
    • @user2768479 我使用了那个,然后我得到一个错误 {"type":"tools.ietf.org/html/... 或出现更多验证错误。","status":400," traceId":"|50c831bb-4dab87ead88f6d56.","errors":{"id":["值 'Gebruikers' 无效。"]}}
    【解决方案2】:

    在动作上添加路由属性。然后,两条路线都将被识别。

    [HttpGet("/Gebruikers")]
    [Route("Gebruikers")]
    public IActionResult GetGebruikers()
    {
        return Ok();
    }
    

    斜杠会忽略控制器上的路由属性,所以它只能识别路由:“https://localhost:5001/Gebruikers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      相关资源
      最近更新 更多