ASP.net - 序列化字典时在客户端上返回无效的 json



这个问题与 Mod 建议的问题不同。 因为我在这里返回一个字符串而不是一个对象。

我正在尝试将 json 字符串发送回客户端。但是它是无效的(格式不正确(关于如何解决此问题的任何建议?

这是服务器端

[HttpGet]
public string foo()
{
Dictionary<string, string> response = new Dictionary<string, string>();
response["itemID"] = "ABC";
return JsonConvert.SerializeObject(response);
}

在客户端,我正在这样做

using (WebClient client = new WebClient())
{
string clientResponse = client.DownloadString(url);
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(clientResponse);
}

clientRepsonse 显然没有正确格式化 json,就像这样(如下所示(。这就是为什么它不能被去皮化

"{"itemID":"ABC"}"

关于我如何解决此问题的任何建议。 在视觉工作室的当地人中,它看起来像这样""{\"itemID\":\"ABC\"}"" 在预览中看起来像这样"{"itemID":"ABC"}"

尝试将 [Produces("application/json"(] 添加到控制器级别。

[Produces("application/json")]
public class MyController : ControllerBase

最新更新