NSwag生成C#客户端时禁用可空参数空值检查的方法
问题描述
我在使用NSwag生成C#客户端时遇到问题:API控制器通过[FromForm] SomeObject x接收包含可空(可选)值类型参数的模型,原始模型和生成的客户端模型中这些字段都是可空类型,但NSwag生成的客户端代码却给可空参数添加了强制空值检查——当传入null时会直接抛出ArgumentNullException,示例代码如下:
public virtual async System.Threading.Tasks.Task<Attachment> UploadAsync(int? idProject = null, int? idTicket = null...) { // ... if (idProject == null) throw new System.ArgumentNullException("idProject"); else { content_.Add(new System.Net.Http.StringContent(ConvertToString(idProject, System.Globalization.CultureInfo.InvariantCulture)), "IdProject"); } // ... }
对应的Swagger JSON Schema中,这些可空参数仅标记了类型,未明确nullable: true:
"/Attachment/Upload": { "post": { "tags": [ "Attachment" ], "requestBody": { "content": { "multipart/form-data": { "schema": { "required": [ "Name" ], "type": "object", "properties": { "IdProject": { "type": "integer", "format": "int32" }, "IdTicket": { "type": "integer", "format": "int32" } // ... } } } } } } }
我已经尝试在NSwag的openApiToCSharpClient配置中设置"queryNullValue": "",但没有效果。由于需要同时传输文件和附加数据,必须使用[FromForm],请问如何禁用这些不必要的空值检查?
当前NSwag生成器配置片段:
"openApiToCSharpClient": { "generateClientInterfaces": true, "GenerateClientClasses": true, "useBaseUrl": false, "namespace": "xxxxxxxx.APIClient", "className": "{controller}Client", "operationGenerationMode": "MultipleClientsFromFirstTagAndOperationName", "jsonLibrary": "SystemTextJson", "generateDtoTypes": true, "disposeHttpClient": true, "injectHttpClient": true, "httpClientType": "System.Net.Http.HttpClient", "UseHttpRequestMessageCreationMethod": false, "generateBaseUrlProperty": false, "generateOptionalParameters": true, "parameterArrayType": "System.Collections.Generic.IReadOnlyList", "responseArrayType": "System.Collections.Generic.IReadOnlyList", "generateOptionalPropertiesAsNullable": true, "generateNullableReferenceTypes": true, "output": "Client.g.cs", "generateExceptionClasses": true, "dateType": "System.DateTime", "dateTimeType": "System.DateTime", "queryNullValue": "", "additionalNamespaceUsages": [ "global::APIClient" ] }
解决方案
步骤1:修正Swagger Schema的可空标记
NSwag生成空值检查的核心原因是Swagger Schema中未明确标记这些参数为可空。需要在API端配置Swashbuckle,确保可空值类型的属性在Schema中生成nullable: true:
// 在Program.cs/Startup.cs的Swagger配置中添加 builder.Services.AddSwaggerGen(c => { // 启用非可空引用类型支持(如果项目使用NRT) c.SupportNonNullableReferenceTypes(); // 为值类型可空类型显式生成可空标记 c.MapType<int?>(() => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }); // 其他值类型可空(如long?、bool?等)可按同样方式添加 });
步骤2:调整NSwag生成器配置
在openApiToCSharpClient配置中添加以下关键设置,禁用Form参数的空值检查:
"openApiToCSharpClient": { // 保留原有配置... "formParameterNullHandling": "Ignore", // 忽略Form参数的空值,不添加检查 "requiredParametersMustBeDefined": false, // 允许可选参数不传值 "nullValueHandling": "Ignore" // 序列化时忽略空值 }
验证效果
重新生成客户端代码后,可空参数的空值检查会被移除,当传入null时,对应的Form字段不会被添加到请求中,符合可选参数的预期行为。
内容的提问来源于stack exchange,提问作者nighthawk
相关产品推荐
相关产品推荐

