【问题标题】:ASP.NET - API 400 error on GET requestASP.NET - GET 请求上的 API 400 错误
【发布时间】:2018-08-28 07:33:21
【问题描述】:

我有这个控制器:

namespace Cantrel.Application.CantrelSearchApi.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    public class MonitorsController : Controller
    {
        private readonly IMonitoringApiService monitoringService;
        private readonly IClientsApiService clientsService;
        private readonly ILogger<MonitorsController> logger;

        public MonitorsController(IMonitoringApiService monitoringService,
            IClientsApiService clientsService,
            ILogger<MonitorsController> logger)
        {
            this.monitoringService = monitoringService;
            this.clientsService = clientsService;
            this.logger = logger;
        }

  [HttpGet("{id}")]
    public async Task<IActionResult> Get(string id)
    {
        if (string.IsNullOrEmpty(null))
        {
            return BadRequest("No id was provided. Please provide a valid monitor id or subject id.");
        }

        try
        {
            MonitorDto monitor;

            if (Guid.TryParse(id, out Guid monitorId))
            {
                monitor = await GetByMonitorId(monitorId);
            }
            else
            {
                monitor = await GetBySubjectId(id);
            }

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

            return Json(monitor);
        }
        catch (Exception ex)
        {
            logger.LogError($"[{Request.Path.Value}]: {ex.ToString()}");
            return new StatusCodeResult(500);
        }
    }

我在 Postman 中进行以下调用:

GET: {{api}}/Monitors/ABCDEFGH-1234-4567-8901-ABCDEFGHIJKL

我收到了400 Bad Request 错误消息No id was provided. Please provide a valid monitor id or subject id,而不是预期的信息返回。

我不确定我是否理解这是怎么发生的。该字符串显然既不是 NULL 也不是空的。

如果我应该提供任何其他类的代码来帮助诊断,请告诉我。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api


    【解决方案1】:

    这总是正确的:

            if (string.IsNullOrEmpty(null)) //always true!
            {
                return BadRequest("No id was provided. Please provide a valid monitor id or subject id.");
            }
    

    因此,您将始终收到 BadRequest 响应。您需要将其更改为:

    if (string.IsNullOrEmpty(id))
    

    【讨论】:

    • 哇,想念我是多么的明显和疯狂! @JanR 非常感谢您提供有用的答案,帮助我而不是对我的帖子投反对票并投票关闭它!
    • 当然,现在我收到了 500 内部服务器错误,但我会将其保存到另一个线程!
    • 反对者和接近者 - stackoverflow.com/conduct 。这不是人们犯愚蠢错误的判断区。我承认这对我来说是一个非常明显的疏忽。我感谢 @JanR 帮助我而不是投反对票。
    • 我们都去过那里,不需要判断:)
    • 感谢@JanR - 我有时甚至会犹豫是否在这里发布它的 b/c。不过,像您这样的人以及这里的许多其他乐于助人的人都值得这样做。
    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2011-03-09
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多