ASP.NET-GET请求出现API 400错误

时间:2018-08-27 23:28:30

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

我有这个控制器:

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

我用邮递员打了以下电话:

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也不为空。

请让我知道我是否应该提供其他任何类别的代码来协助诊断。

1 个答案:

答案 0 :(得分: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))