Migrated web service to .NET Core 2.0 and returnin

2019-02-20 12:12发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-20 13:18

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

查看更多
登录 后发表回答