[英]How do I return a json file from a C# .net web service?
I have a web service method that gets an escaped json string from an external source that I want to allow my users to download as a file by hitting a web service URL. I have a web service method that gets an escaped json string from an external source that I want to allow my users to download as a file by hitting a web service URL. I don't want to save the file on my local web server, just hand a file to the client.我不想将文件保存在本地 web 服务器上,只需将文件交给客户端即可。
IService服务
[OperationContract]
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
string GetEscapedStringFromOutsideSource();
Service服务
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;
}
If I do this then when the user hits service URL with their browser a file is downloaded, but it contains an escaped JSON string rather than valid JSON.如果我这样做,那么当用户使用浏览器点击服务 URL 时,会下载一个文件,但它包含一个转义的 JSON 字符串,而不是有效的 Z0ECD11C1D7A287401D148A23BBD7A2F8。
What I get in the file: "{\"Layout\":{\"Children\":[{\"AftSTA\":928.0}]}}"
我在文件中得到的内容: "{\"Layout\":{\"Children\":[{\"AftSTA\":928.0}]}}"
What I want in the file: {"Layout":{"Children":[{"AftSTA":928.0}]}}
我想要的文件: {"Layout":{"Children":[{"AftSTA":928.0}]}}
Any idea how to escape the resulting string?知道如何转义生成的字符串吗?
Thanks to @dbc for setting me in the right direction.感谢@dbc 让我朝着正确的方向前进。 My final solution for returning a non-escaped json file was simply我返回非转义 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.