ricosuter / nswag Goto Github PK
View Code? Open in Web Editor NEWThe Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
Home Page: http://NSwag.org
License: MIT License
The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
Home Page: http://NSwag.org
License: MIT License
My Web api (WebApi2) service returns json without default values. If for instance an int value is 0 or a bool is false it is not included in the json string returned.
In the response classes that NSwag returns some values have Required = Required.Always, but that gives troubles with the missing values I think it should be Required=Required.Default unless the original response classes have required values.
Also check if this feature is related to the File type
Provide option to choose the action methods to generate...
I'm trying to load a WebAPI project DLL in NSwagStudio and keep receiving this error:
Could not load file or assembly 'System.Web.Http', Version=4.0.0.0...or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
I am running Swashbuckle which is a fork of Swagger - not sure if this is supported. It appears to have some reliance on System.Web.Http version 4.0.0.0 but the binding redirects in web.config redirect it to 5.2.3.
I attempted to resolve by:
Any idea as to how to get past this issue? The solution builds and runs in VS2013 without errors or warnings so I'm not sure why the mismatch is occurring.
Thanks
If the client is used in a asp.net request the httpclient calls ends in deadlock. To avoid that all httpclient calls should look something like this:
var response = await client.PostAsync(url, new StringContent("")).ConfigureAwait(false);
properly best if this is configurable, via the prepareRequest partial method.
Hi, thanks a lot for your very fast reaction on the last issue!
After looking through the generated code, I think that you do not support header parameters, right? Maybe this would be a nice extension for the converter?
Additionally, if a parameter includes the "-" sign, it is taken as it is, which apparently is wrong in TypeScript. Imagine a parameter that is named "X-User" (which is common for header parameters), this will be translated to a variable named "X-User", which is an error in TypeScript. Maybe it should be converted to XUser (if no other parameter with that name exists) or something similar?
Again, this is more like an enhancement request that allows to support header parameters.
Hey,
Thanks for creating this awesome project! I just integrated it into our development environment for generating the types our WebApi exposed for our Typescript project. It was exactly was I was looking for!
I am currently generating only types, not xhr class definitions because we use a framework (Aurelia) for our Typescript project and do not use jquery. Also, we would like some other code bits injected in our xhr's (for example for file upload progress etc).
I dug into your source code and noticed you use template files to generate the code (you currently use it to differentiate between Callbacks and Q). Would it be possible to add a method for us to allow us to use our own custom template file?
It's not a "must" in our current sprint so I don't have time to impelment it myself. If you don't have time, I might implement this in the future if we would require the functionality. However, I think this might be usefull for many others using NSwag to be able to define how they would like thier xhr request code to be generated (especially if you don't want to use the default jquery interface, or for people who would like to use the new fetch api instead of xhr).
Regards,
Maarten
Hi. I'm trying to use NSwag to write a Linqpad Swagger Driver. I'm running into a problem when I generate a client against https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v2.0/json/petstore-expanded.json
The generated methods are of return type Task<SomeType>
but the method contains return default( Error );
which fails to compile as Error doesn't cast to SomeType.
I would reccomend
Remove \n and \r from summary and description values
When a web service does not return any object, the onSuccess method is not called in the process* methods.
Example (this is the code that is currently generated):
private processRemoveElement(xhr: any, onSuccess?: any, onFail?: any) {
var data = xhr.responseText;
var status = xhr.status.toString();
{
var result: any = null;
try {
result = <any>jQuery.parseJSON(data);
} catch(e) {
if (onFail !== undefined)
onFail(null, "error_parsing", e);
return;
}
if (onFail !== undefined)
onFail(result, "error_exception");
}
}
Instead, the generated code could look like follows (note that these void methods might return the http status code 204 instead of 200):
private processRemoveElement(xhr: any, onSuccess?: any, onFail?: any) {
var data = xhr.responseText;
var status = xhr.status.toString();
if (status === "200" || status === "204") {
if (onSuccess !== undefined)
{
onSuccess();
}
return;
}
}
Alternatively, the onSuccess method could use the status code as parameter. Additionally, the onFail method should be called if the status is not 2XX.
An example JSON file looks like this:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Test API"
},
"host": "localhost:8080",
"basePath": "/",
"tags": [
{
"name": "api"
}
],
"schemes": [
"http"
],
"paths": {
"/removeElement": {
"delete": {
"tags": [
"api"
],
"summary": "Removes an element",
"description": "Removes an element",
"operationId": "removeElement",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "X-User",
"in": "header",
"description": "User identifier",
"required": true,
"type": "string"
},
{
"name": "elementId",
"in": "query",
"description": "The id of an existing element that should be removed",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
}
},
"definitions" : { }
}
Edit: Added "definitions": { } to the example JSON file. This is necessary for NSwag.
Hi, I tried to use it to create a TypeScript client (from a swagger.json), but was not successful, then I tried the petshop example (http://petstore.swagger.io/v2/swagger.json), but this also did not work (even after removing the "tag" field which gives the first error).
It would be great, if more different swagger.json files would be supported, but for a start, it would be nice, if the "official" example swagger.json is supported.
Generate a client method for each route attribute
[Route("foo/bar")]
[Route("bar/foo")]
public void MyAction()
{
}
When setting enum handling to "Integer" and parsing an enum which inherits from byte, the code throws and exeption.
Example:
public enum PermissionFlags : byte
{
Create = 0x01,
Read = 0x02,
Update = 0x04,
Delete = 0x08,
}
The exception occurs in NJsonSchema (line 237 of JsonScheamGenerator of NJsonSchema version NJsonSchema.1.18.5821.36806).
They changed NJsonSchema code since that verion (version 1.22 is the most recent as of this post) and swapped around a bit of code, it is now on line 248 of that same file. I will post an issue with NJsonSchema and post a link to that later.
Thanks again for your quick response.
After the introduction of optional parameters, sometimes invalid TypeScript is generated, for example:
{
"swagger" : "2.0",
"info" : {
"version" : "1.0.2",
"title" : "Test API"
},
"host" : "localhost:8080",
"basePath" : "/",
"tags" : [ {
"name" : "api"
} ],
"schemes" : [ "http" ],
"paths" : {
"/removeElement" : {
"delete" : {
"tags" : [ "api" ],
"summary" : "Removes elements",
"description" : "Removes elements",
"operationId" : "removeElement",
"consumes" : [ "application/json" ],
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "X-User",
"in" : "header",
"description" : "User identifier",
"required" : true,
"type" : "string"
}, {
"name" : "elementId",
"in" : "query",
"description" : "The ids of existing elements that should be removed",
"required" : false,
"type" : "integer",
}, {
"name" : "nameId",
"in" : "query",
"description" : "The name id that should be removed",
"required" : true,
"type" : "integer",
} ],
"responses" : {
"default" : {
"description" : "successful operation"
}
}
}
}
},
"definitions" : { }
}
Generates:
(...)
/**
* Removes elements
* @x_User User identifier
* @elementId The ids of existing elements that should be removed
* @nameId The name id that should be removed
* @return successful operation
*/
removeElement(x_User: string, elementId?: number, nameId: number, onSuccess?: (result: any) => void, onFail?: (exception: string, reason: string) => void) {
(...)
This is invalid in TypeScript since elementId cannot be optional, when followed by a required parameter. The _?_ behind _elementId_ should be removed...
If you want to keep the _"required" : true_ vs. _"required" : "false"_ semantics, the code generation could be changed in such a way that the lines
if (elementId !== undefined && elementId !== null)
for each element are only created, when the parameter was set to optional (_"required" : false_). Of course this is optional and does not directly relate to the issue I am describing here.
If a method returns file content/byte[] the return type of the client side method is set to object. and While deserialzing the string response of the API to object, it errors out.
Here is the Server side method code.
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content= new ByteArrayContent(btResult); ;
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = strFileName;
return response;
And here is the method code generated
public async Task<Object> Documents_GetDocumentContentAsync(long fileid, CancellationToken cancellationToken)
{
var url = string.Format("{0}/{1}?", BaseUrl, "api/Documents/{fileid}/Content/");
url = url.Replace("{DocumentID}", fileid.ToString());
var client = new HttpClient();
PrepareRequest(client);
var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false);
ProcessResponse(client, response);
var responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var status = ((int)response.StatusCode).ToString();
if (status == "200")
{
var result = default(Object);
try
{
if (!string.IsNullOrEmpty(responseData))
result = JsonConvert.DeserializeObject<Object>(responseData);
return result;
}
catch (Exception exception)
{
throw new SwaggerException("Could not deserialize the response body.", response.StatusCode, exception);
}
}
else
{
}
throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response.StatusCode + ").", response.StatusCode, null);
}
It errors out on line
result = JsonConvert.DeserializeObject<Object>(responseData);
How can I access these methods ?
"\/Date(1198908717056)\/"
by replacing all matches with new Date(...)
: http://weblogs.asp.net/bleroy/dates-and-jsonJSON.parse(text[, reviver])
:var text = response.text();
var data = JSON.parse(text, this.reviver);
Date/time revivier function: http://stackoverflow.com/questions/1792865/how-to-use-json-parse-reviver-parameter-to-parse-date-string
The default reviver function should implement 1. from this list...
I'm trying to load a WebAPI project DLL and keep receiving this error:
Could not load file or assembly 'System.Web.Http', Version=4.0.0.0...or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
I attempted to resolve by:
Still seeing the same issue. Any idea as to how to get past this issue? The solution builds and runs perfectly so I'm not sure why the mismatch is occurring.
Thanks,
Chris
I'm trying to load a WebAPI project DLL in NSwagStudio and keep receiving this error:
Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest
definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
line 64 of WebApiAssemblyToSwaggerGenerator throws SerializationException because it tries to directly serialize the IEnumerable. Maybe convert to array or list first?
I am getting this error. When I tried to download code and get this signed, it started complaining about NJsonSchema.CodeGenerator is not signed and so no. I don't want to keep on signing all the assemblies.
What do you think would be better way to get around this?
Thanks for the addition of header parameters, I actually wanted to create a more sophisticated example such that a test case can be created out of it, but I faced another bug that was introduced somewhere between version 1.14 and 1.15.
NSwag hangs in an endless loop, if this swagger json should be converted:
{
"swagger" : "2.0",
"info" : {
"version" : "1.0.0",
"title" : "Example API"
},
"host" : "localhost:8081",
"basePath" : "/example",
"tags" : [ {
"name" : "api"
} ],
"schemes" : [ "http" ],
"paths" : {
"/getNotification/{id}" : {
"get" : {
"tags" : [ "api" ],
"summary" : "Gets the content of a notification",
"description" : "",
"operationId" : "getNotification",
"consumes" : [ "application/json" ],
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "id",
"in" : "path",
"description" : "Unique id of the notification",
"required" : true,
"type" : "integer",
"format" : "int64"
} ],
"responses" : {
"200" : {
"description" : "successful operation",
"schema" : {
"$ref" : "#/definitions/DeviceNotification"
}
},
"404" : {
"description" : "Notification not found"
}
}
}
},
},
"definitions" : {
"DeviceNotification" : {
"type" : "object",
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64",
"xml" : {
"attribute" : true
}
},
"message" : {
"type" : "string",
"xml" : {
"attribute" : true
}
},
"stringAttribute2" : {
"type" : "string",
"xml" : {
"attribute" : true
}
},
"arrayIntAttribute" : {
"type" : "array",
"uniqueItems" : true,
"items" : {
"type" : "integer",
"format" : "int64"
}
},
"type" : {
"type" : "string",
"xml" : {
"attribute" : true
},
"enum" : [ "TYPE_1", "TYPE_2" ]
}
}
}
}
}
..
Hi is here any support for this in Asp.net Core (dnx/dotnet)?
Generate Swagger spec for all Web API controllers in an assembly
Open tasks:
built-in angular2 typescript template is not suitable for me. how to use customized template?
Hi,
I'm trying to get hold of NSwag but none of the download links appear to be working for the zip downloads (both from the links on GitHub and AppVeyor)
Hi, me again!
I don't actually need/want the automated set of AJAX calls, just the interface types. Would it be possible to add a switch to include or exclude them?
Probably more of a feature request than an issue, but would be great.
Thanks!
Hello again,
When setting "DefaultEnumHandling" to "EnumHandling.String" in the WebApiToSwaggerGenerator, and then using the "SwaggerToTypeScriptGenerator" to generate typescript, enums are outputted incorrectly;
Example:
export enum WebcamImageOrientation
{
Default = <any>"Default",
Rotate90 = <any>"Rotate90",
Rotate180 = <any>"Rotate180",
Rotate270 = <any>"Rotate270",
}
Is outputted from the C# enum
enum WebcamImageOrientation
{
Default
Rotate90,
Rotate180,
Rotate270,
}
The typescript variant is not valid typescript (Generates TS1066 "Ambient enum elements can only have integer literal initializers.")
If i set the swagger spec to use numbers, the entire enum is gone and types being an enum type in C# result in being a number in Typescript. I do want to use the Typescript enum definitions (so not just use the number which represents the enum value).
I suggest changing generated enums to:
export enum WebcamImageOrientation
{
Default,
Rotate90,
Rotate180,
Rotate270,
}
Hi,
no download link you`ve posted works. All i get as a response is {"message":"Specified cloud file not found."}..
When i try build from source its missing files :
Error 1 Source file 'Commands\AssemblyTypeToSwaggerCommand.cs' could not be found.
Dear,
I'm doing some tests with the swagger specification generation from a web api assembly written in C#.
I take the json output file generated by NSwagStudio, and I try to validate it against the Swagger 2.0 schema (https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v2.0/schema.json).
It fails and give me these errors :
Property 'Get' has not been defined and the schema does not allow additional properties. Property 'typeName' has not been defined and the schema does not allow additional properties. Property 'enumNames' has not been defined and the schema does not allow additional properties.
When using the Swagger Editor online, I receive the same messages.
Could you please tell me what I'm doing wrong or how can I avoid this ?
Thanks for the info.
Web API 2.2 supported indeed(http://stackoverflow.com/a/19989344)
Is possible support this as well?
Dear Author;
I found a bug, If I use code as follow to generate swagger json.
and use swagger to parse the json, but the CC model schema is wrong.
Correctly is
{
"address": "string",
"lastName": "string",
"firstName": "string"
}
but it shows as below
{
"firstName": "string"
}
public class AA
{
public string FirstName { get; set; }
}
public class BB : AA
{
public string LastName { get; set; }
}
public class CC : BB
{
public string Address { get; set; }
}
public class PersonsController : ApiController
{
public void Post([FromBody]CC value)
{
}
}
Hi
When generating the TypeScript definitions, the property names are appearing verbatim. I am using the DataMember attribute but it does not appear in the output. I can see in the NJsonSchema that each property does respect the attribute, so I'm not sure what is going wrong.
Here is a sample class:
[DataContract]
public class InformationData
{
[DataMember(Name = "a")]
public string Code { get; set; }
[DataMember(Name = "b")]
public string InfoText { get; set; }
[DataMember(Name = "c")]
public DateTime ModifiedDate { get; set; }
}
C# WebAPI:
.. Get([FromUri] ComplexType request) { ...}
typescript :
Get(req.prop1: req.prop1, req.prop2: req.prop2, ...) { ... } // invalid syntax
If a parameter is not required, the TypeScript client still requires it as a parameter. This might be unavoidable, since in TS and JS, it is only possible to leave out the last parameters (which makes sense).
Nevertheless, the generated TypeScript client should check if these optional parameters are undef, null, etc. and leave them out, such that the client can be called when these parameters are set to null.
This shows the currently generated code:
removeElement(x_User: string, elementId: number, onSuccess?: (result: any) => void, onFail?: (exception: string, reason: string) => void) {
var url = this.baseUrl + "/removeElement?";
url += "elementId=" + encodeURIComponent("" + elementId) + "&";
var content = "";
$.ajax({
url: url,
beforeSend: this.beforeSend,
type: "delete",
data: content,
dataType: "text",
headers: {
"X-User": x_User,
"Content-Type": "application/json; charset=UTF-8"
}
}).done((data, textStatus, xhr) => {
this.processRemoveElement(xhr, onSuccess, onFail);
}).fail((xhr) => {
this.processRemoveElement(xhr, onSuccess, onFail);
});
}
This is the modified code:
removeElement(x_User: string, elementId: number, onSuccess?: (result: any) => void, onFail?: (exception: string, reason: string) => void) {
var url = this.baseUrl + "/removeElement?";
if(elementId)
{
url += "elementId=" + encodeURIComponent("" + elementId) + "&";
}
var content = "";
$.ajax({
url: url,
beforeSend: this.beforeSend,
type: "delete",
data: content,
dataType: "text",
headers: {
"X-User": x_User,
"Content-Type": "application/json; charset=UTF-8"
}
}).done((data, textStatus, xhr) => {
this.processRemoveElement(xhr, onSuccess, onFail);
}).fail((xhr) => {
this.processRemoveElement(xhr, onSuccess, onFail);
});
}
This is an example JSON file:
{
"swagger" : "2.0",
"info" : {
"version" : "1.0.2",
"title" : "Test API"
},
"host" : "localhost:8080",
"basePath" : "/",
"tags" : [ {
"name" : "api"
} ],
"schemes" : [ "http" ],
"paths" : {
"/removeElement" : {
"delete" : {
"tags" : [ "api" ],
"summary" : "Removes an element",
"description" : "Removes an element",
"operationId" : "removeElement",
"consumes" : [ "application/json" ],
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "X-User",
"in" : "header",
"description" : "User identifier",
"required" : true,
"type" : "string"
}, {
"name" : "elementId",
"in" : "query",
"description" : "The id of an existing element that should be removed",
"required" : false,
"type" : "integer",
"format" : "int64"
} ],
"responses" : {
"default" : {
"description" : "successful operation"
}
}
}
}
},
"definitions" : { }
}
Note: In this example the non-required parameter is also the last parameter, but - in general - this is not the case.
Edit: Added "definitions": { } to the example JSON file. This is necessary for NSwag.
If I omit the /baseclassname: parameter in the commandline utility the generated class gets an class definition with an extra :
like
public partial class myservice :
{
Another thing that I'm correcting by hand at the moment is the merging of enum classes. Sometimes, identical enums are created several times (because the json file describes them several times). Merging them would be nice, although might be a little bit more complicated than resolving small code generation error issues.
Consider this json file:
{
"swagger" : "2.0",
"info" : {
"version" : "1.0.2",
"title" : "Test API"
},
"host" : "localhost:8080",
"basePath" : "/",
"tags" : [ {
"name" : "api"
} ],
"schemes" : [ "http" ],
"paths" : {
"/removeElement" : {
"delete" : {
"tags" : [ "api" ],
"summary" : "Removes elements",
"description" : "Removes elements",
"operationId" : "removeElement",
"consumes" : [ "application/json" ],
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "X-User",
"in" : "header",
"description" : "User identifier",
"required" : true,
"type" : "string"
}, {
"name" : "elementId",
"in" : "query",
"description" : "The ids of existing elements that should be removed",
"required" : false,
"type" : "integer",
}, {
"name" : "nameId",
"in" : "query",
"description" : "The name id that should be removed",
"required" : true,
"type" : "integer",
}, {
"name" : "removeElementWeekdays",
"in" : "query",
"description" : "The weekdays this notification should be removed",
"required" : true,
"type" : "array",
"items" : {
"type" : "string",
"enum" : [ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" ] },
"collectionFormat" : "multi"
}
],
"responses" : {
"200" : {
"description" : "successful operation",
"schema" : {
"$ref" : "#/definitions/Element"
}
},
"404" : {
"description" : "404"
}
}
}
}
},
"definitions" : {
"Element" : {
"type" : "object",
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64",
"xml" : {
"attribute" : true
}
},
"removeDay" : {
"type" : "string",
"xml" : {
"attribute" : true
},
"enum" : [ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" ],
}
}
},
}
}
The enum will be created twice while it could have been merged.
export interface Element {
id?: number;
removeDay?: removeDay;
}
export enum Anonymous
{
MONDAY = <any>"MONDAY",
TUESDAY = <any>"TUESDAY",
WEDNESDAY = <any>"WEDNESDAY",
THURSDAY = <any>"THURSDAY",
FRIDAY = <any>"FRIDAY",
SATURDAY = <any>"SATURDAY",
SUNDAY = <any>"SUNDAY",
}
export enum removeDay
{
MONDAY = <any>"MONDAY",
TUESDAY = <any>"TUESDAY",
WEDNESDAY = <any>"WEDNESDAY",
THURSDAY = <any>"THURSDAY",
FRIDAY = <any>"FRIDAY",
SATURDAY = <any>"SATURDAY",
SUNDAY = <any>"SUNDAY",
}
Of course, this is not an issue that creates invalid code, nevertheless, merging identical enums might be something that you want to consider as a feature for NSwag.
Thanks again for providing this useful tool!
I used NSwag to generate a TypeScript Angular 2 client for my .NET Web API service via a swagger.json file.
Some of my DTOs contain date fields that are formatted as ISO date strings in json.
The swagger definition of the fields look like this:
"BeginDateTime": {
"format": "date-time",
"type": "string"
},
This is the field in the generated TypeScript interface:
BeginDateTime?: Date;
And the JSON object:
{
...,
"BeginDateTime": "2016-04-19T18:03:40.887",
...
}
The problem is that Json.parse()
does not convert the date string to a JavaScript date object. When I want to use date specific functions like dto.BeginDateTime.getHours()
it's no problem at compile time but crashes at runtime.
I can also not simply do a new Date(dto.BeginDateTime)
because it would cause a TypeScript compile error. The workaround is new Date(<any>dto.BeginDateTime)
and that's not the way we should use TypeScript.
What is your preferred way to handle this? Why does the generated client not use a reviver function to parse the date? Or at least allow me to inject a function or service that can do this.
Any possibility of supporting examples for the request/response in the resulting swagger?
My preference would be that the examples be included as a ref in xml documentation, or as a strongly typed instance of the request/response object defined as an attribute (it would have to be a compile time constant, so the request and response example object would need to be a class that inherits from the actual request/response type with a default constructor that supplies values).
My service is RESTFul so my base url looks like '/api/profile'. A GET to that request should fetch all profiles and a POST should create a new one. Using the Angular Typescript template, two methods are created with the same name which is invalid.
The service should look at the HTTP Verb and prepend the method name with a helper like getProfiles and saveProfile.
Currently, NSwag only supports none-array query parameters, the code generation needs to be changed to support arrays.
The following swagger file
{
"swagger" : "2.0",
"info" : {
"version" : "1.0.2",
"title" : "Test API"
},
"host" : "localhost:8080",
"basePath" : "/",
"tags" : [ {
"name" : "api"
} ],
"schemes" : [ "http" ],
"paths" : {
"/removeElement" : {
"delete" : {
"tags" : [ "api" ],
"summary" : "Removes elements",
"description" : "Removes elements",
"operationId" : "removeElement",
"consumes" : [ "application/json" ],
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "X-User",
"in" : "header",
"description" : "User identifier",
"required" : true,
"type" : "string"
}, {
"name" : "elementId",
"in" : "query",
"description" : "The ids of existing elements that should be removed",
"required" : false,
"type" : "array",
"items" : {
"type" : "integer",
"format" : "int64"
},
} ],
"responses" : {
"default" : {
"description" : "successful operation"
}
}
}
}
},
"definitions" : { }
}
Generates the following typescript code:
/**
* Removes elements
* @x_User User identifier
* @elementId The ids of existing elements that should be removed
* @return successful operation
*/
removeElement(x_User: string, elementId?: number[], onSuccess?: (result: any) => void, onFail?: (exception: string, reason: string) => void) {
var url = this.baseUrl + "/removeElement?";
if (elementId !== undefined && elementId !== null)
url += "elementId=" + encodeURIComponent("" + elementId) + "&";
(...)
Instead, it should be iterated over the array:
/**
* Removes elements
* @x_User User identifier
* @elementId The ids of existing elements that should be removed
* @return successful operation
*/
removeElement(x_User: string, elementId?: number[], onSuccess?: (result: any) => void, onFail?: (exception: string, reason: string) => void) {
var url = this.baseUrl + "/removeElement?";
if (elementId !== undefined && elementId !== null)
{
elementId.forEach((arrayElement)=> {
url+="elementId=" + encodeURIComponent("" + arrayElement) +"&";
});
}
First, the client code generator is awesome thanks for that!
Are there any plans in motion to create a WebAPI controller server generator ?
Similar to what swagger-codegen provides for JAX-RS on the JAVA side?
The following should (imho) throw an exception with an error message like
var settings = new WebApiAssemblyToSwaggerGeneratorSettings
{
AssemblyPath = @"value/path/to/assembly.dll",
DefaultUrlTemplate = "api/{controller}/{action}/{id}"
};
var generator = new WebApiAssemblyToSwaggerGenerator(settings);
var swaggerService = generator.GenerateForController("NonExistingClass");
Hi Again!
I have successfully generated the T4 Typescript. It looks good. Except that it only has the types for the parameters to the WebAPI Controller methods. The return types in the Typescript are all "(result: any) " but I have marked my controller methods with things like "[ResponseType(typeof(SyncDataResponse))]". Is it possible to get these as types as well?
Thanks!
Hi
I've had a bit of trouble getting the T4 templates to work. Could you provide a full sample with a TypeScript Generator? When I create a new Text Transform in VS, "SyncTypes.tt", save it, it generates "SyncTypes.cs", which just has a lot of C# code that doesn't compile.
Here is my code. At a minimum I had to change the references to the NuGet folder, and change the name of the first parameter to controllerClass, it was controllerType "var service = generator.Generate(controllerClass..."
Anyway, thanks for your code, and excuse my issue, this is the first i've created....
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(SolutionDir)\packages\NSwag.CodeGeneration.0.11.5770.31403\lib\net45\NJsonSchema.CodeGeneration.dll" #>
<#@ assembly name="$(SolutionDir)\packages\NJsonSchema.CodeGeneration.1.7.5770.30723\lib\net45\NSwag.CodeGeneration.dll" #>
<#@ assembly name="$(SolutionDir)\packages\NSwag.Core.0.11.5770.31403\lib\net45\NSwag.Core.dll" #>
<#@ import namespace="NSwag.CodeGeneration" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="Microsoft.CSharp" #>
<#@ import namespace="NSwag.CodeGeneration.ClientGenerators.TypeScript" #>
<#@ import namespace="NSwag.CodeGeneration.SwaggerGenerators.WebApi" #>
<#@ output extension=".ts" #>
<#
// CONFIGURATION
var assemblyPath = @"../bin/.WebApi.dll";
var controllerClass = ".WebApi.Controllers.MobileController";
var urlTemplate = "api/{controller}/{action}/{id}";
// -------------
var fullAssemblyPath = Path.GetFullPath(Path.GetDirectoryName(Host.TemplateFile) + assemblyPath);
var generator = new WebApiAssemblyToSwaggerGenerator(assemblyPath);
var service = generator.Generate(controllerClass, urlTemplate);
var generatorTS = new SwaggerToTypeScriptGenerator(service);
var provider = new CSharpCodeProvider();
generatorTS.Class = provider.CreateEscapedIdentifier(Path.GetFileNameWithoutExtension(Host.TemplateFile));
var code = generatorTS.GenerateFile();
#>
<#= code #>
Hi,
It would be great to be able to input a URL (for example: https://example.com/api/swagger/docs) in the Swagger specification input text area and load the specification from that endpoint.
Thanks for a great tool
instead of multiple exception types. Useful when using TS versions which do not support "union" types
Add cancellation token to C# clients
See ClientGeneratorBase.cs
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.