我有一个带有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方法。
1条答案
按热度按时间sczxawaw1#
要使modalityId参数可选,您可以为参数使用可空类型,如下所示: