用C#asp.net打印json

Dex*_*ter 2 c# asp.net ajax json themes

好吧,所以我有一些jQuery代码将向aspx文件发送一个AJAX请求.

我的Spellchecker.aspx文件如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Spellchecker.aspx.cs" Inherits="Spellchecker" %>
<head id="Head1" runat="server" />
Run Code Online (Sandbox Code Playgroud)

我不得不把这个"头"标签,否则我得到一个关于web.config文件中的"<page theme"的错误(我需要网站中的其他页面).这意味着来自服务器的响应的形式为:<JSON HERE> <head ... />这是错误的,因为代码应该只返回json数据.

在aspx.cs文件中,我在Page_Load中返回一个字典转换为json:

dict.Add("just_json", json_obj);
JavaScriptSerializer serializer = new JavaScriptSerializer(); //creating serializer instance of JavaScriptSerializer class
string json = serializer.Serialize((object)dict);

Response.Write(json);
}
Run Code Online (Sandbox Code Playgroud)

所以在一个警告框中,我看到了json数据,接着是<head id ="Head1"> <link href ..."样式表等.

我怎样才能使它只从aspx返回JSON数据?

更新:我想我想出来了.将Theme =""放在aspx文件的"%Page"标记中似乎禁用了主题!

Jos*_* M. 5

回答你的"我为什么需要head元素"的实际问题 - 因为这是ASP.NET将你的链接放到CSS和一些JavaScript导入的地方.

目前还不清楚你到底要做什么,但看起来你可能想要创建一个Web服务或者将一个方法公开为ScriptMethod.使用ASPX页面输出对AJAX请求的响应是很奇怪的.

查看ScriptMethodsHttpHandlers.

HttpHandlers允许您完全管理响应.因此,您将创建一个处理程序并将其挂钩到"SpellChecker.ashx",处理程序可以直接写入响应流.

public class SpellCheckerHttpHandler : IHttpHandler
{
    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext context)
    {
        //Write out the JSON you want to return.
        string json = GetTheJson();

        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在system.webServer元素内的Web.Config中,添加:

<handlers>
    <add name="SpellChecker" path="~/SpellChecker.ashx" type="MyNamespace.HttpHandlers.SpellCheckerHttpHandler, MyAssembly" />
</handlers>
Run Code Online (Sandbox Code Playgroud)

现在您可以向您的处理程序发出请求http://localhost/SpellChecker.ashx?TextToCheck=xyz.