【问题标题】:Jsonresult / request returning json wrapped in XMLJsonresult / 请求返回包装在 XML 中的 json
【发布时间】:2012-04-02 10:28:19
【问题描述】:

我有一个请求外部网络服务并在此处返回 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>

我已经检查了提琴手中的请求,并且 Accept 标头中只有 xml 值。我怎样才能让它只打印出 json?我正在使用 ASP.NET Web API。我可以在应用程序启动时删除 XML mediatypeformatter,但我可能需要稍后使用它,所以我不认为这是要走的路。

提前致谢

【问题讨论】:

    标签: xml asp.net-mvc json asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

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

    更新

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

    request.Accept = "application/json";
    

    【讨论】:

    • 好的,我已将其更改为返回一个字符串 - 但它仍然相同。用 XML 包裹的 Json。
    • 你是说 rep.GetMakes() 返回一个字符串吗?也请查看我关于您的客户请求的更新。
    • 是的 rep.getmakes() 返回一个字符串。我不认为我可以返回一个对象,因为数据会根据我从哪里得到它而发生很大变化。
    • 是的,那是正确的,我只是一个白痴,当我在 fiddler 中手工制作请求时,它从默认为 application/xml 的浏览器加载它可以找到。它的第二个问题是 JSON 字符串引号被转义了吗?感谢您到目前为止的帮助
    • @tpeczek 我有类似的问题.. 你能检查一下并给我一个解决方案吗stackoverflow.com/questions/13558856/…
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多