如何使用NSwag防止查询字符串中的空值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用NSwag防止查询字符串中的空值相关的知识,希望对你有一定的参考价值。

我使用NSwag生成TypeScript代码。当我在Web API中使用可为null的int时,生成的nswag代码将发送null。

如何防止NSwag生成此代码或允许.NET Core 3.1将其接受为有效值?

http://localhost:4000/api/SurveyManagement/UpdateRouteSurvey?toSurveyId=null

生成的TypeScript代码:

updateRouteSurvey(toSurveyId: number | null): Observable<void> 
        let url_ = this.baseUrl + "/api/SurveyManagement/UpdateRouteSurvey?";
        if (toSurveyId === undefined)
            throw new Error("The parameter 'toSurveyId' must be defined.");
        else
            url_ += "toSurveyId=" + encodeURIComponent("" + toSurveyId) + "&"; 
        url_ = url_.replace(/[?&]$/, "");
...

C#API接口

  [HttpPost(nameof(UpdateRouteSurvey))]
        public async Task UpdateRouteSurvey(int? toSurveyId) =>
            await _manageSurveyService.UpdateRouteSurvey(toSurveyId);

NSwag配置

 "openApiToTypeScriptClient": 
      "className": "controllerClient",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 2.7,
      "template": "Angular",
      "promiseType": "Promise",
      "httpClass": "HttpClient",
      "useSingletonProvider": false,
      "injectionTokenType": "InjectionToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "Date",
      "nullValue": "Null",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "SwaggerException",
      "clientBaseClass": null,
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": null,
      "useTransformOptionsMethod": false,
      "useTransformResultMethod": false,
      "generateDtoTypes": true,
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "markOptionalProperties": false,
      "generateCloneMethod": false,
      "typeStyle": "Interface",
      "classTypes": [],
      "extendedClasses": [],
      "extensionCode": null,
      "generateDefaultValues": false,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateConstructorInterface": true,
      "convertConstructorInterfaceData": false,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": false,
      "baseUrlTokenName": "API_BASE_URL",
      "queryNullValue": "",
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,

    
答案

我找到了创建正确的空处理的解决方案。

使用NSwag,可以定义自己的模板。首先在nswag.config中设置模板目录,然后在此目录中创建一个文件Client.RequestUrl.liquid,其内容如下:>

let url_ = this.baseUrl + "/ operation.Path % if operation.HasQueryParameters %?% endif %";
% for parameter in operation.PathParameters -%
%     if parameter.IsRequired -%
if ( parameter.VariableName  === undefined ||  parameter.VariableName  === null)
    throw new Error("The parameter ' parameter.VariableName ' must be defined.");
%     else -%
if ( parameter.VariableName  !== null &&  parameter.VariableName  !== undefined)
%     endif -%
%     if parameter.IsDateOrDateTimeArray -%
url_ = url_.replace(" ""  parameter.Name ", encodeURIComponent( parameter.VariableName .map(s_ => s_ ? s_.toJSON() : "null").join()));
%     elseif parameter.IsDateOrDateTime -%
url_ = url_.replace(" ""  parameter.Name ", encodeURIComponent( parameter.VariableName  ? "" +  parameter.VariableName .toJSON() : "null"));
%     elseif parameter.IsArray -%
url_ = url_.replace(" ""  parameter.Name ", encodeURIComponent( parameter.VariableName .join()));
%     else -%
url_ = url_.replace(" ""  parameter.Name ", encodeURIComponent("" +  parameter.VariableName ));
%     endif -%
%     if parameter.IsOptional -%
else
    url_ = url_.replace("/ ""  parameter.Name ", "");
%     endif -%
% endfor -%
% for parameter in operation.QueryParameters -%
%     if parameter.IsRequired -%
%         if parameter.IsNullable -%
if ( parameter.VariableName  === undefined)
    throw new Error("The parameter ' parameter.VariableName ' must be defined.");
else
%         else -%
if ( parameter.VariableName  === undefined ||  parameter.VariableName  === null)
    throw new Error("The parameter ' parameter.VariableName ' must be defined and cannot be null.");
else
%         endif -%
%     else -%
%         if parameter.IsNullable -%
if ( parameter.VariableName  !== undefined)
%         else -%
if ( parameter.VariableName  === null)
    throw new Error("The parameter ' parameter.VariableName ' cannot be null.");
else if ( parameter.VariableName  !== undefined)
%         endif -%
%     endif -%
%     if parameter.IsDateOrDateTimeArray -%
     parameter.VariableName  &&  parameter.VariableName .forEach(item_ =>  url_ += " parameter.Name =" + encodeURIComponent(item_ ? "" + item_.toJSON() : "null") + "&"; );
%     elseif parameter.IsObjectArray -%
     parameter.VariableName  &&  parameter.VariableName .forEach((item, index) => 
        for (let attr in item)
            if (item.hasOwnProperty(attr)) 
                url_ += " parameter.Name [" + index + "]." + attr + "=" + encodeURIComponent("" + (<any>item)[attr]) + "&";
            
    );
%     elseif parameter.IsDateOrDateTime -%
    url_ += " parameter.Name =" + encodeURIComponent( parameter.VariableName  ? "" +  parameter.VariableName .toJSON() : " QueryNullValue ") + "&";
%     elseif parameter.IsArray -%
     parameter.VariableName  &&  parameter.VariableName .forEach(item =>  url_ += " parameter.Name =" + encodeURIComponent("" + item) + "&"; );
%     else -%
    url_ += " parameter.Name =" + ( parameter.VariableName  !== null ? encodeURIComponent("" +  parameter.VariableName ) : '') + "&";
%     endif -%
% endfor -%
url_ = url_.replace(/[?&]$/, "");

以上是关于如何使用NSwag防止查询字符串中的空值的主要内容,如果未能解决你的问题,请参考以下文章

如何序列化数组中的空值?

使用mysql中的select语句替换sql中的空值?

在 MySql 中,如何将 csv 文件中的 sql 字符串中的空值导出为双引号(“”)?

如何写sql语句去掉oracle返回结果中的空值(NULL)

如何使用文本框搜索功能返回同一列中的空值和值

如何从列类型列表中删除 pandas DataFrame 中的空值