简体   繁体   中英

ASP.NET - API 400 error on GET request

I have this Controller:

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

I make the following call in Postman:

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

Instead of the expected return of information on that monitor I receive a 400 Bad Request error with the message No id was provided. Please provide a valid monitor id or subject id No id was provided. Please provide a valid monitor id or subject id .

I'm not sure I understand how this is happening. The string is clearly neither NULL or empty.

Please let me know if there is any other classes' code I should provide to assist in diagnosis.

This is always true:

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

Thus you will always get a BadRequest response. You will need to change it to:

if (string.IsNullOrEmpty(id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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