Skip to content

Instantly share code, notes, and snippets.

@molnarm
Created November 29, 2018 08:20
Show Gist options
  • Select an option

  • Save molnarm/d6a844756fc36b44bc00e3cec9d56b40 to your computer and use it in GitHub Desktop.

Select an option

Save molnarm/d6a844756fc36b44bc00e3cec9d56b40 to your computer and use it in GitHub Desktop.
NSswag with operation with multiple successful responses
//----------------------
// <auto-generated>
// Generated using the NSwag toolchain v11.18.7.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
namespace Custom
{
#pragma warning disable // Disable all warnings
[System.CodeDom.Compiler.GeneratedCode("NSwag", "11.18.7.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")]
public partial interface IClient
{
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
System.Threading.Tasks.Task<Entity> TestPostAsync(System.Guid orderId);
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
Entity TestPost(System.Guid orderId);
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
System.Threading.Tasks.Task<Entity> TestPostAsync(System.Guid orderId, System.Threading.CancellationToken cancellationToken);
}
[System.CodeDom.Compiler.GeneratedCode("NSwag", "11.18.7.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class Client : BaseCustomClient, IClient
{
private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
public Client(string baseUrl)
{
BaseUrl = baseUrl;
_settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() =>
{
var settings = new Newtonsoft.Json.JsonSerializerSettings();
UpdateJsonSerializerSettings(settings);
return settings;
});
}
protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } }
partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings);
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<Entity> TestPostAsync(System.Guid orderId)
{
return TestPostAsync(orderId, System.Threading.CancellationToken.None);
}
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
public Entity TestPost(System.Guid orderId)
{
return System.Threading.Tasks.Task.Run(async () => await TestPostAsync(orderId, System.Threading.CancellationToken.None)).GetAwaiter().GetResult();
}
/// <summary>Summary.</summary>
/// <returns>An entity was successfully created.</returns>
/// <exception cref="CustomException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public async System.Threading.Tasks.Task<Entity> TestPostAsync(System.Guid orderId, System.Threading.CancellationToken cancellationToken)
{
var resource = "/test";
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append(resource);
var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false);
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json");
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);
PrepareRequest(client_, request_, url_, resource);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
ProcessResponse(client_, response_);
ProcessResponse(client_, response_, url_, resource);
var status_ = ((int)response_.StatusCode).ToString();
if (status_ == "201")
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(Entity);
try
{
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Entity>(responseData_, _settings.Value);
return result_;
}
catch (System.Exception exception_)
{
throw new CustomException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
}
else
if (status_ == "202")
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(RequestStatus);
try
{
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestStatus>(responseData_, _settings.Value);
}
catch (System.Exception exception_)
{
throw new CustomException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new CustomException<RequestStatus>("The request is still being processed.", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
var result_ = default(Error);
try
{
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Error>(responseData_, _settings.Value);
}
catch (System.Exception exception_)
{
throw new CustomException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
}
throw new CustomException<Error>("Default response", (int)response_.StatusCode, responseData_, headers_, result_, null);
}
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
}
finally
{
if (client_ != null)
client_.Dispose();
}
}
private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value is System.Enum)
{
string name = System.Enum.GetName(value.GetType(), value);
if (name != null)
{
var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name);
if (field != null)
{
var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute))
as System.Runtime.Serialization.EnumMemberAttribute;
if (attribute != null)
{
return attribute.Value;
}
}
}
}
else if (value is byte[])
{
return System.Convert.ToBase64String((byte[]) value);
}
else if (value != null && value.GetType().IsArray)
{
var array = System.Linq.Enumerable.OfType<object>((System.Array) value);
return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo)));
}
return System.Convert.ToString(value, cultureInfo);
}
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")]
[System.Serializable]
public partial class RequestStatus
{
[Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string Status { get; set; }
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")]
[System.Serializable]
public partial class Entity
{
[Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Guid? Id { get; set; }
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")]
[System.Serializable]
public partial class Error
{
[Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string Message { get; set; }
}
[System.CodeDom.Compiler.GeneratedCode("NSwag", "11.18.7.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class CustomException : System.Exception
{
public int StatusCode { get; private set; }
public string Response { get; private set; }
public System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; }
public CustomException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException)
: base(message, innerException)
{
StatusCode = statusCode;
Response = response;
Headers = headers;
}
public override string ToString()
{
return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString());
}
}
[System.CodeDom.Compiler.GeneratedCode("NSwag", "11.18.7.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class CustomException<TResult> : CustomException
{
public TResult Result { get; private set; }
public CustomException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result, System.Exception innerException)
: base(message, statusCode, response, headers, innerException)
{
Result = result;
}
}
}
swagger: '2.0'
info:
title: Multiple responses issue
version: v0.0.1
paths:
/test:
post:
summary: Summary.
description: Description.
parameters:
- name: orderId
required: true
type: string
format: uuid
responses:
"201":
description: An entity was successfully created.
schema:
$ref: '#/definitions/Entity'
"202":
description: The request is still being processed.
schema:
$ref: '#/definitions/RequestStatus'
default:
description: Default response
schema:
$ref: '#/definitions/Error'
definitions:
RequestStatus:
type: object
properties:
status:
type: string
Entity:
type: object
properties:
id:
type: string
format: uuid
Error:
type: object
properties:
message:
type: string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment