如何在C# 6 Minimal API中设置FromHeader参数为可选?
实现Minimal API中FromHeader参数的可选性
可以实现将accountId设为可选参数,以下是两种可行方案:
方案一:使用可空值类型(区分“未传Header”和“传了空Guid”)
将accountId的类型改为Guid?并设置默认值为null,当请求中不存在指定Header时,参数会被赋值为null:
public static void MapGetInstallationByIngressEndpoint(this WebApplication app) => app.MapPost(Url, async ( [FromBody] GetInstallationByIngressRequest getInstallationByIngressRequest, [FromHeader(Name = Constants.AssetIdHeader)] Guid? accountId = null, [FromHeader(Name = Constants.CorrIdHeader)] Guid correlationId, [FromServices] IRequestHandler<GetInstallationByIngressRequest, InstallationQueryResult> requestHandler, [FromServices] IValidator<GetInstallationByIngressRequest> requestValidator, CancellationToken cancellationToken) => { // 后续逻辑中可通过accountId.HasValue判断是否传入了Header if (accountId.HasValue) { // 使用accountId.Value处理业务逻辑 } // ... });
方案二:设置默认值为Guid.Empty(不区分“未传”和“传空值”)
如果不需要区分请求是否携带该Header,仅需要一个默认值,可以将参数类型保留为Guid并设置默认值为default(Guid)(即Guid.Empty):
public static void MapGetInstallationByIngressEndpoint(this WebApplication app) => app.MapPost(Url, async ( [FromBody] GetInstallationByIngressRequest getInstallationByIngressRequest, [FromHeader(Name = Constants.AssetIdHeader)] Guid accountId = default, [FromHeader(Name = Constants.CorrIdHeader)] Guid correlationId, [FromServices] IRequestHandler<GetInstallationByIngressRequest, InstallationQueryResult> requestHandler, [FromServices] IValidator<GetInstallationByIngressRequest> requestValidator, CancellationToken cancellationToken) => { // 判断accountId是否为Guid.Empty来处理逻辑 if (accountId != Guid.Empty) { // 执行对应业务逻辑 } // ... });
注意事项
如果之前设置Guid?仍报错,检查是否存在全局模型验证规则强制要求该Header必须存在,或者是否在请求验证逻辑中额外校验了该参数的必填性,需要对应调整验证逻辑。
内容的提问来源于stack exchange,提问作者Bjoern
相关产品推荐
相关产品推荐

