ashx返回一个xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace WEB
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null);
            doc.AppendChild(dec);
            //创建一个根节点(一级)
            XmlElement root = doc.CreateElement("First");
            doc.AppendChild(root);
            //创建节点(二级)
            XmlNode node = doc.CreateElement("Seconde");
            //创建节点(三级)
            XmlElement element1 = doc.CreateElement("Third1");
            element1.SetAttribute("Name", "Sam");
            element1.SetAttribute("ID", "665");
            element1.InnerText = "Sam Comment";
            node.AppendChild(element1);

            XmlElement element2 = doc.CreateElement("Third2");
            element2.SetAttribute("Name", "Round");
            element2.SetAttribute("ID", "678");
            element2.InnerText = "Round Comment";
            node.AppendChild(element2);

           

            root.AppendChild(node);
            context.Response.Write(doc.OuterXml);
        }
    }
}

 

转载于:https://www.cnblogs.com/ryan-wan/archive/2012/09/21/2696888.html

首先,ASHX文件是一种用于处理HTTP请求的处理程序,因此我们需要定义一个实现IHttpHandler接口的类来处理客户端请求。 下面是一个简单的示例。假设我们的ASHX文件名为MyHandler.ashx: ```csharp using System; using System.Web; public class MyHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { // 获取客户端请求的方法 string method = context.Request.HttpMethod; if (method == "GET") { // 处理GET请求 string name = context.Request.QueryString["name"]; context.Response.Write("Hello, " + name + "!"); } else if (method == "POST") { // 处理POST请求 string data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd(); context.Response.Write("Received data: " + data); } else { // 不支持的请求方法 context.Response.StatusCode = 405; // Method Not Allowed } } public bool IsReusable { get { return false; } } } ``` 在上面的代码中,我们实现了IHttpHandler接口,并覆盖了它的ProcessRequest方法,用于处理客户端请求。我们首先获取请求的方法(GET或POST),然后根据不同的方法执行不同的操作。 对于GET请求,我们从查询字符串中获取“name”参数,并向客户端返回一个简单的问候消息。 对于POST请求,我们从请求正文中读取数据,并向客户端返回一个简单的响应消息。 最后,我们还需要将这个处理程序注册到Web.config文件中,以便IIS能够找到它: ```xml <configuration> <system.web> <httpHandlers> <add verb="*" path="MyHandler.ashx" type="MyHandler"/> </httpHandlers> </system.web> </configuration> ``` 在上面的示例中,我们将MyHandler类注册为能够处理所有HTTP请求方法(verb="*"),并将它的路径设置为MyHandler.ashx。 这样,我们就可以通过发送GET或POST请求到MyHandler.ashx来测试我们的处理程序了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值