NSwag: C# client throwing exception trying to Deserialize a json response into a string

I am using an externally generated swagger.json definition that returns json data as a string. The client is failing with an exception calling DeserializeObject in the following code

 if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
                            var result_ = default(string);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(responseData_, _settings.Value);
                                return result_;
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }
                        }

The call to DeserializeObject fails (and is not required) when the result is also a string. The result should just be set to the reponseData value.

Whats the best way to accomplish this? Do I need to update templates?

Thanks.

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

A string like foobar is not valid JSON, only "foobar" is

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =>
    {
        // requires using Microsoft.AspNetCore.Mvc.Formatters;
        options.OutputFormatters.RemoveType<StringOutputFormatter>();
        options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
    });
}

image

https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-6.0

This can be fixed on the server side of the API