c# - 如何从 C# .net Web 服务返回 json 文件?
问题描述
我有一个 Web 服务方法,它从外部源获取转义的 json 字符串,我希望允许我的用户通过点击 Web 服务 URL 将其作为文件下载。我不想将文件保存在本地 Web 服务器上,只需将文件交给客户端即可。
服务
[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}]}}
知道如何转义生成的字符串吗?
解决方案
感谢@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));
}
推荐阅读
- java - 如何在firebase数据库中添加数据?
- python - 如何以“file://///SERVER//folder1/folder2/”的形式获取路径
- java - 三星健康:解决 java.lang.IllegalArgumentException: heart_rate (READ) is invalid
- html - 如何先缩小大的 flex-box 儿童?
- heroku - Heroku 空闲,因为配额已用完
- android - 颤动中TabBar视图中的传递方法
- html - 如何在 Angular 子组件选择器之间传递内容
- cookieconsent - 删除 ngx-cookieconsent 创建的 cookie 策略弹出窗口
- service-worker - Angular 7 - 服务工作者不会注册
- android-studio - 从 Spek 1.x 迁移到 Spek 2.x 错误