将Web服务迁移到.NET Core 2.0并返回json
我已将我的Web服务迁移到.NET Core 2.0,它工作正常,但我有问题得到响应为json字符串。
关于api的方法:
[HttpGet] [ProducesResponseType(typeof(string), 200)] [ProducesResponseType(typeof(EntityNotFoundErrorResult), 404)] public async Task GetCurrenciesAsync() { var result = await service.GetByTypeAsync(ObjectType.Currency.ToString()); return Ok(result); }
返回正确的json作为result
:
"{"elements": [{"Id": "1", "Symbol": "PLN"},{"Id": "2", "Symbol": "SIT"}]}"
然后在客户端我使用服务堆栈将我的货币作为字符串:
public virtual IEnumerable GetCurrencies() { string response = null; try { response = api.Get("/Currencies"); } catch (Exception e) { } return string.IsNullOrEmpty(response) ? null : JsonConvert.DeserializeObject(response).elements; }
response
看起来像这样:
""{\"elements\": [{\"Id\": \"1\", \"Symbol\": \"PLN\"},{\"Id\": \"2\", \"Symbol\": \"SIT\"}]}""
所以JsonConvert.DeserializeObject
抛出反序列化exception:
Newtonsoft.Json.JsonSerializationException
但是当我反复对sting做出反应并且然后反对时,它就有用了:
var x = JsonConvert.DeserializeObject(response); var deserialized = JsonConvert.DeserializeObject(x).elements;
我猜这个问题是在客户端吗? 奇怪的是它在.NET Core 1.1上运行得很好
我错过了什么?
好吧,似乎在.NET Core 2.0 [Produces("application/json")]
已经改变,它正在将字符串输出序列化为json,所以我将它序列化了两次…这个os的解决方案替换了[Produces("application/json")]
和[Produces("text/plain")]
使用方法/控制器
上述就是C#学习教程:将Web服务迁移到.NET Core 2.0并返回json分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1024491.html