【问题标题】:How do I return a json file from a C# .net web service?如何从 C# .net Web 服务返回 json 文件?
【发布时间】:2021-02-09 16:44:01
【问题描述】:

我有一个 Web 服务方法,它从外部源获取转义的 json 字符串,我希望允许我的用户通过点击 Web 服务 URL 将其作为文件下载。我不想将文件保存在本地 Web 服务器上,只需将文件交给客户端即可。

IService

[OperationContract]
    [WebInvoke(Method = "GET", 
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    string GetEscapedStringFromOutsideSource();

服务

public string SendUserAFile()
{
    string s = GetEscapedStringFromOutsideSource();

    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + Effectivity + ".json");
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

    return s;
}

如果我这样做,那么当用户使用浏览器点击服务 URL 时,会下载一个文件,但它包含转义的 JSON 字符串而不是有效的 JSON。

我在文件中得到的内容: "{\"Layout\":{\"Children\":[{\"AftSTA\":928.0}]}}"

我想要的文件:{"Layout":{"Children":[{"AftSTA":928.0}]}}

知道如何转义生成的字符串吗?

【问题讨论】:

  • 我有一个从外部源获取转义 json 字符串的 Web 服务方法是什么意思?你的意思是s 包含字符串"{\"Layout\":{\"Children\":[{\"AftSTA\":928.0}]}}"?或者s 是否包含{"Layout":{"Children":[{"AftSTA":928.0}]}} 并且当您使用return s 时它会以某种方式被转义?
  • 如果是前者,那看起来是双序列化的 JSON。您可以使用您首选的 JSON 序列化程序来反序列化该字符串并获取原始 JSON,例如JsonConvert.DeserializeObject<string>(s)。 (或者您可以请求该服务修复 JSON...)
  • 如果是后者,您应该可以使用WebOperationContext.Current.CreateTextResponse 返回原始JSON,详情请参阅Oleg 的this answer 到How to set Json.Net as the default serializer for WCF REST service。
  • @dbc 我认为 s 不是双序列化的。例如,我可以使用 Newtonsoft 像 JObject j = JObject.Parse(s); 那样解析它,然后从中得到一个有效的 JObject。我的问题是,当我在文本编辑器中打开生成的 json 文件时,它仍然被转义。
  • 好的,那么 Web 服务不会返回转义的 JSON 字符串,而是当您返回它时,您的代码会以某种方式对其进行转义。在这种情况下,请尝试使用WebOperationContext.Current.CreateTextResponse 答案,看看是否对您有帮助。 ...另一个类似的问答在这里:How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string, wrapped in quotes?.

标签: c# json escaping


【解决方案1】:

感谢@dbc 让我朝着正确的方向前进。我返回非转义 json 文件的最终解决方案很简单

public Stream SendUserAFile()
{
    string s = GetEscapedStringFromOutsideSource();
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + Effectivity + ".json");
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s));
}

【讨论】:

  • 您也可以在返回类型上使用 Content() 和 IActionResult :)
猜你喜欢
  • 2013-04-08
  • 2012-07-11
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
相关资源
最近更新 更多