基于 NSwagStudio 改写的 WebAPI 转 OpenAPI 代理生成工具,按需自定义生成调用代理方法, NSwag是一个用于.NET、TypeScript和其他平台的Swagger 2.0 API工具链,用C#编写。其中OpenAPI/Swagger规范使用JSON和JSON模式来描述RESTful web API。该项目提供了从这些Swagger自动生成客户端代码的工具并将这一代集成到现工作流中.
NSwag | NJsonSchema | Apimundo | Namotion.Reflection
//----------------------
// <auto-generated>
// Generated using the CRB.TPM.OpenAPIGenerator v1.0.0.0
// </auto-generated>
//----------------------
using System.CodeDom.Compiler;
using System.Globalization;
[GeneratedCode("CRB.TPM", "CRB.TPM.OpenAPIGenerator v1.0.0.0")]
public partial class CommonClient
{
private string _baseUrl = "http://localhost:6220";
private HttpClient _httpClient;
private System.Lazy<JsonSerializerSettings> _settings;
public CommonClient(HttpClient httpClient)
{
_httpClient = httpClient;
_settings = new System.Lazy<JsonSerializerSettings>(CreateSerializerSettings);
}
private JsonSerializerSettings CreateSerializerSettings()
{
var settings = new JsonSerializerSettings();
UpdateJsonSerializerSettings(settings);
return settings;
}
public string BaseUrl
{
get { return _baseUrl; }
set { _baseUrl = value; }
}
protected JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } }
partial void UpdateJsonSerializerSettings(JsonSerializerSettings settings);
partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url);
partial void PrepareRequest(HttpClient client, HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
partial void ProcessResponse(HttpClient client, HttpResponseMessage response);
/// <summary>
/// 账户类型下拉列表
/// </summary>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual Task<ResultModel<dynamic>> AccountTypeSelectAsync()
{
return AccountTypeSelectAsync(System.Threading.CancellationToken.None);
}
protected struct ObjectResponseResult<T>
{
public ObjectResponseResult(T responseObject, string responseText)
{
this.Object = responseObject;
this.Text = responseText;
}
public T Object { get; }
public string Text { get; }
}
public bool ReadResponseAsString { get; set; }
protected virtual async Task<ObjectResponseResult<T>> ReadObjectResponseAsync<T>(HttpResponseMessage response, IReadOnlyDictionary<string, IEnumerable<string>> headers, System.Threading.CancellationToken cancellationToken)
{
if (response == null || response.Content == null)
{
return new ObjectResponseResult<T>(default(T), string.Empty);
}
if (ReadResponseAsString)
{
var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
var typedBody = JsonConvert.DeserializeObject<T>(responseText, JsonSerializerSettings);
return new ObjectResponseResult<T>(typedBody, responseText);
}
catch (JsonException exception)
{
var message = "Could not deserialize the response body string as " + typeof(T).FullName + ".";
throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception);
}
}
else
{
try
{
using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var streamReader = new System.IO.StreamReader(responseStream))
using (var jsonTextReader = new JsonTextReader(streamReader))
{
var serializer = JsonSerializer.Create(JsonSerializerSettings);
var typedBody = serializer.Deserialize<T>(jsonTextReader);
return new ObjectResponseResult<T>(typedBody, string.Empty);
}
}
catch (JsonException exception)
{
//Could not create an instance of type CRB.TPM.Mod.Admin.IResultModel. Type is an interface or abstract class and cannot be instantiated. Path 'successful', line 1, position 14.”
var message = "Could not deserialize the response body stream as " + typeof(T).FullName + ".";
throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception);
}
}
}
private string ConvertToString(object value, CultureInfo cultureInfo)
{
if (value == null)
{
return "";
}
if (value is System.Enum)
{
var name = System.Enum.GetName(value.GetType(), value);
if (name != null)
{
var field = IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name);
if (field != null)
{
var attribute = CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute))
as System.Runtime.Serialization.EnumMemberAttribute;
if (attribute != null)
{
return attribute.Value != null ? attribute.Value : name;
}
}
var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo));
return converted == null ? string.Empty : converted;
}
}
else if (value is bool)
{
return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant();
}
else if (value is byte[])
{
return System.Convert.ToBase64String((byte[])value);
}
else if (value.GetType().IsArray)
{
var array = Enumerable.OfType<object>((System.Array)value);
return string.Join(",", Enumerable.Select(array, o => ConvertToString(o, cultureInfo)));
}
var result = System.Convert.ToString(value, cultureInfo);
return result == null ? "" : result;
}
}
namespace OpenAPI.Tests
{
using CRB.TPM.Mod.Admin;
using CommonClient = CRB.TPM.Mod.Admin.CommonClient;
public class AdminTest
{
protected CommonClient _commonClient;
[SetUp]
public void Setup()
{
var http = new HttpClient(new HttpClientHandler());
http.DefaultRequestHeaders.Add("ApiKey", "8e421ff965cb4935ba56ef7833bf4750");
_commonClient = new CommonClient(http)
{
ReadResponseAsString = true
};
}
[Test]
public async Task AccountClientTest()
{
var result = await _commonClient.AccountTypeSelectAsync();
Assert.True(result.Successful);
}
}
}