Search code examples
c#asp.netasp.net-mvcapiasp.net-web-api

Why do I get a "Field is Required" error from my API even tough the query parameter is optional?


I have an API with a ProfessionalsController, within this controller I have this method:

    [HttpGet]
    [Authorize]
    public async Task<ActionResult<GetProfessionalsQueryResponse>> GetAllAsync([FromQuery]string modalityId = "")
    {
        return Ok(await _mediator.Send(new GetProfessionalsQuery { ModalityId = modalityId }));
    }

This is the response that I get from the server when I call the endpoint:

{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-501a973003a36918de9e22ee2bab9936-73e986dd9121e81a-00", "errors": { "modalityId": [ "The modalityId field is required." ] } }

When I give a value to the modalityId parameter I get the filtered results from the API, but when I don't provide a parameter I get this error. But shouldn't the fact that I set an empty string in the argument make it an optional parameter?

This is my Program.cs class:

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddApplicationServices();

        builder.Services.AddPersistenceServices(builder.Configuration);

        builder.Services.AddInfrastructureServices(builder.Configuration);

        builder.Services.AddHttpContextAccessor();

        builder.Services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        });

        builder.Services.AddCors(options =>
        {
            options.AddPolicy("Open", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
        });

        builder.Services.AddEndpointsApiExplorer();

        builder.Services.AddSwaggerGen();

        var app = builder.Build();
     
        app.UseSwagger();

        app.UseSwaggerUI();

        app.UseHttpsRedirection();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseMiddleware<ExceptionHandlerMiddleware>();

        app.MapControllers();

        app.Run();
    }
}

On my GetProfessionalsQuery I don't have any validation. Also, when I debug the execution doesn't even hits the GetAllAsync method.


Solution

  • To make the modalityId parameter optional, you can use a nullable type for the parameter like this:

    public async Task<ActionResult<GetProfessionalsQueryResponse>> GetAllAsync([FromQuery] string? modalityId = null)
    {
       
    }