0

I am trying to generate some client code from a swagger.json file and the methods created by NSwag do not have any return types as you can see below:

Can anyone tell me what I might be doing wrong? This is my first time using NSwag to consume/generate client code for a swagger API.

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
    /// <param name="wallet">The Wallet Address, that the operation should be performed on.</param>
    /// <param name="page">Show this page number.</param>
    /// <param name="limit">Show this many results per page.</param>
    /// <param name="sortAsc">Sort by this field, ascending.</param>
    /// <param name="sortDesc">Sort by this field, descending.</param>
    /// <param name="filter">Filter by these field=value combinations. Performs an exact string comparison. e.g.
    /// <br/>- AND - `?filter=name=Bob&amp;filter=age=30`
    /// <br/>- OR - `?filter=id=[1,abc,true]`
    /// <br/>- NESTED - `?filter=params.owner=1`</param>
    /// <returns>Successful</returns>
    /// <exception cref="ApiException">A server side error occurred.</exception>
    public virtual async System.Threading.Tasks.Task ApiFarmlandListAsync(string wallet = null, double? page = null, double? limit = null, string sortAsc = null, string sortDesc = null, System.Collections.Generic.IEnumerable<string> filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
    {
        var urlBuilder_ = new System.Text.StringBuilder();
        urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/farmland/list?");

        if (wallet != null)
        {
            urlBuilder_.Append(System.Uri.EscapeDataString("wallet") + "=").Append(System.Uri.EscapeDataString(ConvertToString(wallet, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
        }

        if (page != null)
        {
            urlBuilder_.Append(System.Uri.EscapeDataString("page") + "=").Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
        }

        if (limit != null)
        {
            urlBuilder_.Append(System.Uri.EscapeDataString("limit") + "=").Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
        }

        if (sortAsc != null)
        {
            urlBuilder_.Append(System.Uri.EscapeDataString("sortAsc") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sortAsc, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
        }

        if (sortDesc != null)
        {
            urlBuilder_.Append(System.Uri.EscapeDataString("sortDesc") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sortDesc, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
        }

        if (filter != null)
        {
            foreach (var item_ in filter) { urlBuilder_.Append(System.Uri.EscapeDataString("filter") + "=").Append(System.Uri.EscapeDataString(ConvertToString(item_, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); }
        }

        urlBuilder_.Length--;

        var client_ = new System.Net.Http.HttpClient();
        var disposeClient_ = true;

        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);
                var disposeResponse_ = true;

                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;

                    if (status_ == 200)
                    {
                        return;
                    }
                    else
                    {
                        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 (" + status_ + ").", status_, responseData_, headers_, null);
                    }
                }
                finally
                {
                    if (disposeResponse_)
                        response_.Dispose();
                }
            }
        }
        finally
        {
            if (disposeClient_)
                client_.Dispose();
        }
    }

Here is a piece from the swagger.json file. (Note, I have no control over how this file is created)

"/api/farmland/list": {
  "get": {
    "produces": [
      "application/json"
    ],
    "parameters": [
      {
        "$ref": "#/components/parameters/WalletParameter"
      },
      {
        "$ref": "#/components/parameters/PageParameter"
      },
      {
        "$ref": "#/components/parameters/LimitParameter"
      },
      {
        "$ref": "#/components/parameters/SortAscParameter"
      },
      {
        "$ref": "#/components/parameters/SortDescParameter"
      },
      {
        "$ref": "#/components/parameters/FilterParameter"
      }
    ],
    "tags": [
      "Farmland"
    ],
    "responses": {
      "200": {
        "description": "Successful"
      }
    }
  }
},

2 Answers 2

1

This is because the ProducesResponseType attribute decorating your api action method has missed to specify the type of object being returned, i.e. something like the following.

[ProducesResponseType(StatusCodes.Status200OK)]

What you need to do is specify the type of object being returned by the api action method, like

[ProducesResponseType(typeof(YourExpectedResponseType[]), StatusCodes.Status200OK)]

Once you have that in place, the swagger.json should contain the relevant info and NSwag should be able to generate the expected code.

For e.g. you would see the following additional bit in responses property in your swagger.json

"responses": {
  "200": {
    "description": "Successful",
    "content": {
      "application/json": {
        "schema": {
          "type": "array",
          "items": {
            "$ref": "#/components/schemas/<YourExpectedResponseType>"
          }
        }
      }
    }
  }
}
1
  • this worked for me, thanks! Sep 26, 2023 at 23:16
-1

Your API method ApiFarmlandListAsync should return Task instead of Task type. Set T to your desired return type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.