0

我正在编写一个需要与 SQL 服务器交换一些信息的页面。出于可移植性的原因,并且因为我讨厌编写 ASP,但我被告知要在 IIS 7 服务器上执行此操作,所以我正在用纯 HTML 编写页面,使用 C# .NET 中的通用处理程序 (ASHX) 来执行服务器-侧面的东西,并使用AJAX在它们之间进行通信。我已经让这种方法使用Response.ContentType = "text/plain";,但我想用一个请求返回几条信息,所以我切换到 XML 或 JSON,倾向于 XML。

因此,要返回 XML,我更改为 .NET "text/xml",但是我只是Response.Write逐字记录整个 XML 代码,还是在 .NET 中内置了更简洁的方法?JSON的同样问题。我知道 jQuery(甚至只是 JavaScript)中有用于解析返回数据的特定方法,所以我想知道 .NET 中是否有类似的东西可以编码。

4

1 回答 1

2

但是我只是 Response.Write 整个 XML 代码逐字写入,还是有更简洁的方式内置到 .NET 中?

您可以使用XmlWriterXDocument甚至XmlSerializer来构建 XML,然后将其写入Response.OutputStream.

这是一个带有的示例XDocument

public void ProcessRequest(HttpContext context)
{
    var doc = new XDocument(
        new XElement(
            "messages",
            new XElement(
                "message", 
                new XAttribute("id", "1"), 
                new XAttribute("value", "message 1"), 
            ),
            new XElement(
                "message", 
                new XAttribute("id", "2"), 
                new XAttribute("value", "message 2")
            )
        )
    );
    context.Response.ContentType = "text/xml";
    using (var writer = XmlWriter.Create(context.Response.OutputStream))
    {
        doc.WriteTo(writer);
    }
}

JSON的同样问题

You would use a Json serializer such as JavaScriptSerializer and then write it to the output stream:

public void ProcessRequest(HttpContext context)
{
    var serializer = new JavaScriptSerializer();
    string json = serializer.Serialize(new
    {
        messages = new[]
        {
            new { id = 1, value = "message 1" },
            new { id = 2, value = "message 2" },
        }
    });
    context.Response.ContentType = "application/json";
    context.Response.Write(json);
}

This being said, you should be aware that ASP.NET MVC or the knocking on the door Web API are now the preferred ways to expose such data instead of writing generic handlers.

于 2012-08-15T18:17:07.167 回答