将 Web 服务迁移到 .NET Core 2.0 并返回 json [英] Migrated web service to .NET Core 2.0 and returning json

查看:29
本文介绍了将 Web 服务迁移到 .NET Core 2.0 并返回 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将我的 Web 服务迁移到 .NET Core 2.0,它运行良好,但我无法将响应作为 json 字符串获取.

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

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

即返回正确的 json 作为 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;
    }

response 看起来像这样:

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

所以 JsonConvert.DeserializeObject 抛出反序列化异常:

So JsonConvert.DeserializeObject throws deserialization exception:

Newtonsoft.Json.JsonSerializationException

但是当我反序列化对 sting 和 objest 的响应时它会起作用:

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;

我猜是客户端的问题吧?奇怪的是它在 .NET Core 1.1 上运行得很好

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

我缺少什么?

推荐答案

好吧,看来在 .NET Core 2.0 中 [Produces("application/json")] 已经改变,它正在序列化字符串输出到 json 所以我将它序列化了两次......这个操作系统的解决方案将 [Produces("application/json")] 替换为 [Produces("text/plain")] ovet 方法/控制器

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

这篇关于将 Web 服务迁移到 .NET Core 2.0 并返回 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆