首页 > 解决方案 > 如何从 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}]}}

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

标签: c#jsonescaping

解决方案


感谢@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));
}

推荐阅读