简体   繁体   中英

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 don't want to save the file on my local web server, just hand a file to the client.

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.

What I get in the file: "{\"Layout\":{\"Children\":[{\"AftSTA\":928.0}]}}"

What I want in the file: {"Layout":{"Children":[{"AftSTA":928.0}]}}

Any idea how to escape the resulting string?

Thanks to @dbc for setting me in the right direction. My final solution for returning a non-escaped json file was simply

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM