Jsonresult/request返回用XML包装的json



我有一个请求外部Web服务并在此处返回json的方法:

    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>

我已经在fiddler中检查了请求,Accept标头中只有xml值。我如何才能将其打印出json?我正在使用ASP.NET Web API。我可以在应用程序启动时删除XML mediatypeformatter,但稍后可能需要使用它,所以我认为这不是办法。

提前感谢

您不应该从ApiController操作返回JsonResult。ApiController操作应该返回对象(或集合),MediaTypeFormatters负责将它们序列化为JSON、XML或其他任何内容(基于请求的内容类型)。请看一下这个基本教程。

更新

为了确保客户端正在请求JSON(而不是XML),Web API将尝试使用正确的MediaTypeFormatter,将其添加到您的客户端:

request.Accept = "application/json";

不要在WebMethod中返回字符串,而是使用:

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

最新更新