Base solution for your next web application
Open Closed

consuming/using swagger generated REST API #3390


User avatar
0
rafalpiotrowski created

for those who wnat to connect different applications to the AspNetZero framework using REST API

the API has been auto-generated with Visual Studio 2017 using the "Add -> REST Api Client..." function Client Namespace: AspNetZeroWebHost Swagger Url: <a class="postlink" href="http://localhost:22742/swagger/v1/swagger.json">http://localhost:22742/swagger/v1/swagger.json</a>

then just use the AspNetZeroWebHostClient to call the server

var credentials = new TokenCredentials("what ever here");
                var client = new AspNetZeroWebHost.AspNetZeroWebHostClient(new Uri("http://localhost:22742", UriKind.Absolute), credentials);
                var customHeaders = new Dictionary<string, List<string>>
                {
                    { "Abp.TenantId", new List<string> { "1" } }
                };
                Task<HttpOperationResponse<AuthenticateResultModel>> ar = client.ApiTokenAuthAuthenticatePostWithHttpMessagesAsync(
                    new AspNetZeroWebHost.Models.AuthenticateModel("username", "userpassword"),
                    customHeaders);
                ar.Wait();

                customHeaders.Add("Authorization", new List<string> { "Bearer " + ar.Result.Body.AccessToken });

                var aa = client.ApiTokenAuthGetExternalAuthenticationProvidersGetWithHttpMessagesAsync(customHeaders);
                aa.Wait();

Important thing: The generated code has one problem when deserializing the respinse. Work arround is:

  1. add wrapper class
public static class AnzSafeJsonConvert
    {
        /// <summary>
        /// Wrapper arround SafeJsonConverter.DeserializeObject to parse json return from the AspNetZero Swagger response
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string json, JsonSerializerSettings settings)
        {
            var a = SafeJsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings);
            var b = a.ToArray()[0];
            var jsonResult = b.Value.ToString();
            return SafeJsonConvert.DeserializeObject<T>(jsonResult, settings);
        }
    }

then replace each occurence of:

_result.Body = SafeJsonConvert.DeserializeObject<...

with:

_result.Body = YourProjectNameSpace.AnzSafeJsonConvert.DeserializeObject<...

hope this helps

of course, this is not plug and play so you do need to make some changes to the above code, but I am sure you all will know what to change

if anyone has found better solution, let me know


No answer yet!