Migrated web service to .NET Core 2.0 and returning json

谁说我不能喝 提交于 2019-12-30 07:32:13

问题


I have migrated my web service to .NET Core 2.0, it works fine but I have problem with getting response as json string.

Method on api:

    [HttpGet]
    [ProducesResponseType(typeof(string), 200)]
    [ProducesResponseType(typeof(EntityNotFoundErrorResult), 404)]
    public async Task<IActionResult> GetCurrenciesAsync()
    {
        var result = await service.GetByTypeAsync(ObjectType.Currency.ToString());

        return Ok(result);
    }

that is returning proper json as result:

"{\"elements\": [{\"Id\": \"1\", \"Symbol\": \"PLN\"},{\"Id\": \"2\", \"Symbol\": \"SIT\"}]}"

Then on client I'm using service stack to get my currencies as string:

    public virtual IEnumerable<CurrencyData> GetCurrencies()
    {
        string response = null;

        try
        {
            response = api.Get<string>("/Currencies");
        }
        catch (Exception e)
        {
        }

        return string.IsNullOrEmpty(response) ? null :  JsonConvert.DeserializeObject<TempCurrencyClass>(response).elements;
    }

And the response looks like this:

"\"{\\\"elements\\\": [{\\\"Id\\\": \\\"1\\\", \\\"Symbol\\\": \\\"PLN\\\"},{\\\"Id\\\": \\\"2\\\", \\\"Symbol\\\": \\\"SIT\\\"}]}\""

So JsonConvert.DeserializeObject throws deserialization exception:

Newtonsoft.Json.JsonSerializationException

But it works when I'm deserializing response to sting and to objest then:

var x = JsonConvert.DeserializeObject<string>(response);
var deserialized = JsonConvert.DeserializeObject<TempCurrencyClass>(x).elements;

I'm guessing that the problem is on client right? Well strange thing is that it works just fine on .NET Core 1.1

What I'm missing?


回答1:


Well it appears that in .NET Core 2.0 [Produces("application/json")] has changed and it is serializing string outputs to json so I had it serialized twice... solution for this os to replace [Produces("application/json")] with [Produces("text/plain")] ovet the method / controller



来源:https://stackoverflow.com/questions/46785619/migrated-web-service-to-net-core-2-0-and-returning-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!