簡體   English   中英

Json 字符串在 web-api 中被轉義

[英]Json string gets escaped in web-api

我們將 JSON 配置數據存儲在數據庫中。 我需要獲取這個 JSON 數據並通過 asp.net web-api 將它返回給瀏覽器:

public class ConfigurationController : ApiController
{
    public string Get(string configId)
    {
        // Get json from database
        // when i return the fetched json it get's escaped
    }
}

我返回的值被轉義了。 我如何簡單地返回字符串? 我真的不想填充被序列化為 JSON 的對象。

您可以從 ApiController 返回一個HttpResponseMessage ,它允許您基本上返回一個字符串值。

例如

public HttpResponseMessage Get()
{
    return new HttpResponseMessage() { 
        Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json") 
    };
}

您想要做的只是將 json 字符串作為 StringContent 傳遞。

接受的答案略有偏差。 正確的版本是:

public HttpResponseMessage Get()
{
    return new HttpResponseMessage() { 
        Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json") 
    };
}

正是 StringContent 函數正確地刪除了轉義。 如果沒有 application/json 媒體類型,像 postman 這樣的工具將無法正確顯示結果的“漂亮”版本。

這對我有用:

return Request.CreateResponse( HttpStatusCode.OK, stringContent );
public HttpResponseMessage GetTravelers(string authkey)
{
var json = JsonConvert.SerializeObject(travelList, Global.JsonSettings);
 return new HttpResponseMessage()
 {
   Content = new StringContent(json, System.Text.Encoding.UTF8, 
"text/html")
       };

是的,它的工作你必須將方法類型更改為 HttpResponseMessage Instied of string 或 int 類型

您必須將您的查詢值序列化為 Json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM