Search code examples
asp.net-core.net-coreswaggernswagstudio

Getting the result of Iactionresult in .net Core using nswagger studio


I have this api as you can see :

 [HttpGet("CreateToken")]

    public IActionResult CreateToken()
    {


        string tokenString = string.Empty;

        tokenString = BuildJWTToken();

        return Ok(new { Token = tokenString });
    }

I use nswagger studio to generate my api code as you can see in my MVC core

public System.Threading.Tasks.Task CreateTokenAsync()
        {
            return CreateTokenAsync(System.Threading.CancellationToken.None);
        }

        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Success</returns>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task CreateTokenAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();
            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Default1/CreateToken");

            var client_ = new System.Net.Http.HttpClient();
            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    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_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            return;
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
                            throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                            response_.Dispose();
                    }
                }
            }
            finally
            {
                if (client_ != null)
                    client_.Dispose();
            }
        }

This code is generated by NswaggerStudio . So when I want to call my createtoken API as you can see i couldn't get the token in the result:

public async Task<IActionResult> Index()
    {

        var q = myapi.CreateTokenAsync();
        ViewBag.data = q;
        
        return View(q);
    }

And the view

<div class="text-center">
    <h1 class="display-4">@ViewBag.data</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

And here you can see the result

enter image description here


Solution

  • Unfortunately, you cannot return result in this way.

    To return any model your returning type in method should look like something like this

    [HttpGet("CreateToken")]
    public IActionResult<TokenModel> CreateToken()
    {
        string tokenString = string.Empty;
        tokenString = BuildJWTToken();
        return Ok(new { Token = tokenString });
    }
    

    Check this for more information