2012-04-02 66 views
0

我有請求外部web服務和這裏返回JSON的方法:Jsonresult /請求返回JSON包裹在XML

public string GetJsonRequest(string url) 
    { 
     string response = string.Empty; 
     var request = System.Net.WebRequest.Create(url) as HttpWebRequest; 
     if (request != null) 
     { 
      request.Method = WebRequestMethods.Http.Get; 
      request.Timeout = 20000; 
      request.ContentType = "application/json"; 


      var httpresponse = (HttpWebResponse)request.GetResponse(); 

      using (var streamreader = new StreamReader(httpresponse.GetResponseStream())) 
        response = streamreader.ReadToEnd(); 

      if (httpresponse != null) httpresponse.Close(); 
     } 
     return response; 
    } 

而返回這裏的結果的方法:

public JsonResult Makes()  
    { 
     CarRepository rep = new CarRepository(); 
     return new JsonResult() 
     { 
      Data = rep.GetMakes(), 
      ContentType = "application/json" 
     }; 
    } 

public string Makes()  
    { 
     CarRepository rep = new CarRepository(); 
     return rep.GetMakes(); 
    } 

這將返回正確的json,但它被封裝在XML中

<JsonResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <ContentType>application/json</ContentType> 
    <Data xsi:type="xsd:string"> 
     The JSON data....... 
    </Data> 
    <JsonRequestBehavior>AllowGet</JsonRequestBehavior> 
    <MaxJsonLength xsi:nil="true"/> 
    <RecursionLimit xsi:nil="true"/> 
</JsonResult> 

我已經提琴手檢查請求和接受頭只有XML值。我怎麼能得到這個剛剛打印出來JSON?我正在使用ASP.NET Web API。我可以在應用程序啓動時刪除XML mediatypeformatter,但我可能需要稍後使用它,所以我不認爲這是要走的路。

在此先感謝

回答

2

您不應該從ApiController操作返回JsonResult。 ApiController操作應該返回對象(或集合),MediaTypeFormatters負責將它們序列化爲JSON,XML或其他任何內容(基於請求的內容類型)。請看看這個基本的tutorial

UPDATE

爲了確保客戶端請求的JSON(非XML)和Web API將嘗試使用適當的MediaTypeFormatter添加到您的客戶端:

request.Accept = "application/json"; 
+0

好吧,我已經改變它返回一個字符串 - 但它仍然是一樣的。 Json包裝在XML中。 – gdp 2012-04-02 10:38:29

+0

你是說rep.GetMakes()返回一個字符串嗎?請檢查我的更新關於您的客戶請求也。 – tpeczek 2012-04-02 10:41:52

+0

是rep.getmakes()返回一個字符串。我不認爲我可以返回一個對象,因爲數據變化很大,取決於我從哪裏得到它。 – gdp 2012-04-02 10:49:54

0

,而不是返回的一個字符串在您的WebMethod使用:

JavaScriptSerializer js = new JavaScriptSerializer(); 
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));