【问题标题】:Page returns HTML instead of JSON页面返回 HTML 而不是 JSON
【发布时间】:2018-08-27 19:33:18
【问题描述】:

编译运行后,页面显示有效的 JSON;但是,当使用WebClient 调用同一页面时,整个 HTML 代码都会通过,因此无法解析 JSON。

'ASP Code:
        <%@ Import Namespace="System.IO"%>
        <%@ Import Namespace="System.Data"%>
        <%@ Import Namespace="System.Data.OleDb"%>
        <%Response.AppendHeader("Access-Control-Allow-Origin", "*")
        Response.AppendHeader("Content-type", "application/json")%>
        <%
        Dim conn As OleDbConnection
        Dim objAdapter As OleDbDataAdapter
        Dim objTable As DataTable
        Dim objRow As DataRow
        Dim objDataSet As New DataSet()
        Dim outp
        Dim c
            conn = New OleDbConnection("Provider=sqloledb;Data Source=test\SQLEXPRESS;Initial Catalog=TestDb;User ID=sa;Password=test;OLE DB Services=-2;")
            objAdapter = New OleDbDataAdapter("select * from cars", conn)
        objAdapter.Fill(objDataSet, "myTable")
        objTable=objDataSet.Tables("myTable")

        outp = ""
        c = chr(34)
        for each x in objTable.Rows
        if outp <> "" then outp = outp & ","
                outp = outp & "{" & c & "Make" & c & ":" & c & x("make") & c & ","
                outp = outp & c & "Model" & c & ":" & c & x("model") & c & ","
                outp = outp & c & "Year" & c & ":" & c & x("year") & c & "}"
        next

            outp = "{" & c & "records" & c & ":[" & outp & "]}"

            Response.Write(outp)
            conn.Close()
        %>

        //Json Purser:
            private void btnDeserialize_Click(object sender, EventArgs e)
            {
                System.Net.WebClient client = new System.Net.WebClient();
                string json = client.DownloadString("http://localhost:82");// Expecting JSon, Found HTML

                Cars c= (new JavaScriptSerializer()).Deserialize<Cars>(json);
                MessageBox.Show(c.Make);
            }

【问题讨论】:

  • 真正的答案是你不会那样做。 ASP.NET aspx 文件应该是网页。要仅返回 JSON,您将创建一个 ashx Web 处理程序或 Web 方法。

标签: asp.net json


【解决方案1】:

我通过从我的 ASP 页面中删除所有 HTML 标记并仅留下包含 ASP 代码的表单标记来解决此问题。像魔术一样工作!

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多