将Web服务迁移到.NET Core 2.0并返回json [英] Migrated web service to .NET Core 2.0 and returning 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
但是当我反序列化对刺痛和目标的回应时,它会起作用:
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")]
,以遍历方法/控制器
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屋!