[英]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. 我不想將文件保存在本地 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 字符串,而不是有效的 Z0ECD11C1D7A287401D148A23BBD7A2F8。
我在文件中得到的內容: "{\"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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.