asp.net 为什么坚韧查询参数是可选的,我的API还是会出现“Field is Required”错误?

2nbm6dog  于 2023-04-22  发布在  .NET
关注(0)|答案(1)|浏览(850)

我有一个带有ProfessionalsController的API,在这个控制器中我有这个方法:

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

这是我调用端点时从服务器获得的响应:
{“type”:“https://tools.ietf.org/html/rfc7231#section-6.5.1“,“title”:“出现一个或多个验证错误。",“status”:400,“traceId”:“00- 501 a973003 a36918 de 9 e22 ee 2bab 9936 - 73 e986 dd 9121 e81 a-00”,“错误”:{“modalityId”:[“需要modalityId字段”] } }
当我给予modalityId参数赋值时,我会从API中得到过滤后的结果,但是当我没有提供参数时,我会得到这个错误。但是我在参数中设置了一个空字符串,这难道不应该使它成为一个可选参数吗?
这是我的Program.cs类:

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

在我的GetProfessionalsQuery中,我没有任何验证。而且,当我调试时,执行甚至没有命中GetAllAsync方法。

sczxawaw

sczxawaw1#

要使modalityId参数可选,您可以为参数使用可空类型,如下所示:

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

相关问题