1. 新建.netCore WebApi 項目(選擇Angular)。按照上一篇的加上Swage 文檔,使http://localhost:11934/swagger/v1/swagger.json 能夠訪問。html
2.新建 一個文件夾nswag,裏面有3個文件node
{ "runtime": "Default", "swaggerGenerator": { "fromSwagger": { "url": "http://localhost:11934/swagger/v1/swagger.json", "output": null } }, "codeGenerators": { "swaggerToTypeScriptClient": { "className": "{controller}ServiceProxy", "moduleName": "", "namespace": "", "typeScriptVersion": 2.0, "template": "Angular", "promiseType": "Promise", "httpClass": "HttpClient", "useSingletonProvider": false, "injectionTokenType": "InjectionToken", "rxJsVersion": 6.0, "dateTimeType": "OffsetMomentJS", "nullValue": "Undefined", "generateClientClasses": true, "generateClientInterfaces": false, "generateOptionalParameters": false, "wrapDtoExceptions": false, "wrapResponses": false, "generateResponseClasses": true, "responseClass": "SwaggerResponse", "useTransformOptionsMethod": false, "useTransformResultMethod": false, "generateDtoTypes": true, "operationGenerationMode": "MultipleClientsFromPathSegments", "markOptionalProperties": false, "generateCloneMethod": true, "typeStyle": "Class", "extensionCode": "service.extensions.ts", "generateDefaultValues": true, "excludedTypeNames": [], "handleReferences": false, "generateConstructorInterface": true, "convertConstructorInterfaceData": false, "importRequiredTypes": true, "useGetBaseUrlMethod": false, "baseUrlTokenName": "API_BASE_URL", "queryNullValue": "", "output": "../src/shared/service-proxies/service-proxies.ts" }, "swaggerToCSharpClient": { "generateClientClasses": true, "generateClientInterfaces": false, "generateDtoTypes": true, "injectHttpClient": false, "disposeHttpClient": true, "generateExceptionClasses": true, "exceptionClass": "SwaggerException", "wrapDtoExceptions": true, "useHttpClientCreationMethod": false, "httpClientType": "System.Net.Http.HttpClient", "useHttpRequestMessageCreationMethod": false, "useBaseUrl": true, "generateBaseUrlProperty": true, "generateSyncMethods": false, "exposeJsonSerializerSettings": false, "clientClassAccessModifier": "public", "typeAccessModifier": "public", "generateContractsOutput": false, "parameterDateTimeFormat": "s", "generateUpdateJsonSerializerSettingsMethod": true, "serializeTypeInformation": false, "queryNullValue": "", "className": "{controller}Client", "operationGenerationMode": "MultipleClientsFromOperationId", "generateOptionalParameters": false, "generateJsonMethods": true, "parameterArrayType": "System.Collections.Generic.IEnumerable", "parameterDictionaryType": "System.Collections.Generic.IDictionary", "responseArrayType": "System.Collections.ObjectModel.ObservableCollection", "responseDictionaryType": "System.Collections.Generic.Dictionary", "wrapResponses": false, "generateResponseClasses": true, "responseClass": "SwaggerResponse", "namespace": "MyNamespace", "requiredPropertiesMustBeDefined": true, "dateType": "System.DateTime", "dateTimeType": "System.DateTime", "timeType": "System.TimeSpan", "timeSpanType": "System.TimeSpan", "arrayType": "System.Collections.ObjectModel.ObservableCollection", "dictionaryType": "System.Collections.Generic.Dictionary", "arrayBaseType": "System.Collections.ObjectModel.ObservableCollection", "dictionaryBaseType": "System.Collections.Generic.Dictionary", "classStyle": "Inpc", "generateDefaultValues": true, "generateDataAnnotations": true, "excludedTypeNames": [], "handleReferences": false, "generateImmutableArrayProperties": false, "generateImmutableDictionaryProperties": false, "output": null }, "swaggerToCSharpController": { "controllerStyle": "Partial", "useCancellationToken": false, "aspNetNamespace": "System.Web.Http", "className": "{controller}", "operationGenerationMode": "MultipleClientsFromOperationId", "additionalNamespaceUsages": [ "System.Web.Http" ], "generateOptionalParameters": false, "generateJsonMethods": true, "parameterArrayType": "System.Collections.Generic.IEnumerable", "parameterDictionaryType": "System.Collections.Generic.IDictionary", "responseArrayType": "System.Collections.ObjectModel.ObservableCollection", "responseDictionaryType": "System.Collections.Generic.Dictionary", "wrapResponses": false, "generateResponseClasses": true, "responseClass": "SwaggerResponse", "namespace": "MyNamespace", "requiredPropertiesMustBeDefined": true, "dateType": "System.DateTime", "dateTimeType": "System.DateTime", "timeType": "System.TimeSpan", "timeSpanType": "System.TimeSpan", "arrayType": "System.Collections.Generic.IEnumerable", "dictionaryType": "System.Collections.Generic.Dictionary", "arrayBaseType": "System.Collections.ObjectModel.ObservableCollection", "dictionaryBaseType": "System.Collections.Generic.Dictionary", "classStyle": "Inpc", "generateDefaultValues": true, "generateDataAnnotations": true, "excludedTypeNames": [], "handleReferences": false, "generateImmutableArrayProperties": false, "generateImmutableDictionaryProperties": false, "output": null } } }
3.在package.json 中添加 "nswag": "^11.18.6"npm
執行 npm install .若是安裝不上,能夠改變下倉庫:npm set registry https://registry.npm.taobao.org/ 參考這裏json
4. 運行後端。後端
雙擊運行nswag 下的refresh.bat 就能夠生成 service-proxies.tspromise
5.原理跟蹤:ide
@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\..\nswag\bin\nswag.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node "%~dp0\..\nswag\bin\nswag.js" %* )
nswag.js:
#!/usr/bin/env node "use strict"; var defaultCoreVersion = "11"; var supportedCoreVersions = ["10", "11", "20", "21"]; // Initialize process.title = 'nswag'; console.log("NSwag NPM CLI"); var args = process.argv.splice(2, process.argv.length - 2).map(function (a) { return a.indexOf(" ") === -1 ? a : '"' + a + '"' }).join(" "); // Legacy support args = args.replace("--x86", "/runtime:WinX86"); args = args.replace("/runtime:x86", "/runtime:WinX86"); args = args.replace("--core 1.0", "/runtime:NetCore10"); args = args.replace("--core 1.1", "/runtime:NetCore11"); args = args.replace("--core 2.0", "/runtime:NetCore20"); args = args.replace("--core 2.1", "/runtime:NetCore21"); args = args.replace("--core", "/runtime:NetCore" + defaultCoreVersion); // Search for full .NET installation var hasFullDotNet = false; var fs = require('fs'); if (process.env["windir"]) { try { var stats = fs.lstatSync(process.env["windir"] + '/Microsoft.NET'); if (stats.isDirectory()) hasFullDotNet = true; } catch (e) { console.log(e); } } var c = require('child_process'); if (hasFullDotNet && args.toLowerCase().indexOf("/runtime:netcore") == -1) { // Run full .NET version if (args.toLowerCase().indexOf("/runtime:winx86") != -1) { var cmd = '"' + __dirname + '/binaries/Win/nswag.x86.exe" ' + args; var code = c.execSync(cmd, { stdio: [0, 1, 2] }); } else { var cmd = '"' + __dirname + '/binaries/Win/nswag.exe" ' + args; var code = c.execSync(cmd, { stdio: [0, 1, 2] }); } } else { // Run .NET Core version var defaultCmd = 'dotnet "' + __dirname + '/binaries/NetCore' + defaultCoreVersion + '/dotnet-nswag.dll" ' + args; var infoCmd = "dotnet --version"; c.exec(infoCmd, (error, stdout, stderr) => { for (let version of supportedCoreVersions) { var coreCmd = 'dotnet "' + __dirname + '/binaries/NetCore' + version + '/dotnet-nswag.dll" ' + args; if (args.toLowerCase().indexOf("/runtime:netcore" + version) != -1) { c.execSync(coreCmd, { stdio: [0, 1, 2] }); return; } else { if (!error) { var coreVersion = stdout; if (coreVersion.indexOf(version + ".0") !== -1) { c.execSync(coreCmd, { stdio: [0, 1, 2] }); return; } } } } c.execSync(defaultCmd, { stdio: [0, 1, 2] }); return; }); }