1

I have a ASP.NET controller that controls a schedule (as I'm Brazilian, schedule in Portuguese means Agendamento).

The thing is, I can't allow scheduling the same room (in Portuguese Sala) being taken twice at the same time.

So in the POST request I check the DB to see if that room has already being taken and if it has I want to return only a Json object { "error": "You can't do that." }.

If the request does not have any problem then the insert should be done and the inserted object has to be returned.

[HttpPost]
public async Task<ActionResult<Agendamento>> PostAgendamento(Agendamento agendamento)
{

    var agendamentosJaExistentes = await _context.Agendamentos.Include(ag => ag.Sala)
        .Where(ag =>
                ag.SalaId == agendamento.SalaId &&
                (
                    (agendamento.PeriodoInicial >= ag.PeriodoInicial && agendamento.PeriodoInicial <= ag.PeriodoFinal)
                    ||
                    (agendamento.PeriodoFinal >= ag.PeriodoInicial && agendamento.PeriodoFinal <= ag.PeriodoFinal)
                    ))
        .ToListAsync();

    if (agendamentosJaExistentes != null)
    {
        return ??? JSON OBJECT ???
    }

    _context.Agendamentos.Add(agendamento);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetAgendamento", new { id = agendamento.Id }, agendamento);
}

Can you guys help me?

3 Answers 3

1

Add NewtonsoftJson support

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
                .AddNewtonsoftJson();
    }      

Return JsonObject

       if (agendamentosJaExistentes != null)
        {
            return new ObjectResult(Error("You can't do that.")); //???JSON OBJECT???
        }
 

400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error.

    public class ReturnJson
    {
        public string Status { get; set; }
        public string Message { get; set; }
    }

    public static ReturnJson Error(string responseMessage, string responseCode = "400")
        {
            ReturnJson returnJson = new ReturnJson()
            {
                Status = responseCode,
                Message = responseMessage ?? string.Empty
            };
            return returnJson;
        }

Test Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

For RESTful api one of the best practice is to return errors aligning with HTTP status code. For this specific case probably HTTP 500 (instead of 200 success with an error body) makes more sense.

You can do so by this:

    var result = new
    {
        Error = "Room already booked",
    };
    return this.StatusCode(StatusCodes.Status500InternalServerError, result);

Comments

0

This is a simple way that am using (DoteNet Core 3.x)

return Json(new { error = "Your error message " , status = 405 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.