asp.net获取Post和Get数据的方法

来源:互联网 发布:西北师大知行学院附近宾馆 编辑:程序博客网 时间:2024/04/29 18:08

一、获得Post数据的方法

C# codeCode highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

 

protected void Page_Load(object sender, EventArgs e)

{

Response.Write(GetInput());

}

 

private string GetInput()

{

try

    {

System.IO.Stream s = Request.InputStream;

int count = 0;

byte[] buffer = new byte[1024];

StringBuilder builder = new StringBuilder();

while ((count = s.Read(buffer, 0, 1024)) > 0)

{

builder.Append(Encoding.UTF8.GetString(buffer, 0, count));

}

return builder.ToString();

}

catch (Exception ex)

{

throw ex;

}

}

 

 

自己写的示例

protected void Page_Load(object sender, EventArgs e)

    {

        Stream s = Request.InputStream;

        //Stream提供字节序列的一般视图。

        //Request.InputStream获取传入的 HTTP 实体主体的内容。

 

        byte[] buffer = new byte[1024];//无符号 8 位整数数组

       

        int count = 0;

 

        StringBuilder builder = new StringBuilder();//表示可变字符字符串。

        while ((count = s.Read(buffer, 0, 1024)) > 0)//每次读取1024个字节

        /*Stream的实例方法Read()的语法:

        public abstract int Read (byte[] buffer,int offset,int count)

         *Stream中讨取的字节序列存放在buffer

         *offset,是基于0的字节偏移量,从此处开始存储从当前流中读取的数据

         *count代表从当前流中最多读取的字节数。

         *Read()方法的返回值是读入缓冲区中的总字节数,如果当前可用的字节数没有请求的字节数那么多,

         则总字节数可能小于请求的字节数。

         * 如果已到达流的末尾,则为零 (0)

         */

        {

            builder.Append(Encoding.UTF8.GetString(buffer, 0, count));

            //builder.Append(Encoding.Default.GetString(buffer, 0, count));

            //将字节添加至可变字符字符串

            //GetString方法将一个字节序列解码为一个字符串。

        }

        string name = builder.ToString();       

        HttpResponse hr = HttpContext.Current.Response;       

        hr.Clear();

        hr.Write(name);

        hr.Flush();

        hr.End();

}

 

 

 

二、获取Get数据的方法

       string strName = HttpContext.Current.Request.QueryString["name"];

// QueryString可获得url中的参数           

string strRes = "This is the response from the server:/r/n" + "Hello, " + strName + "!";

       HttpContext.Current.Response.Clear();//清除缓冲区流中的所有内容输出。

       HttpContext.Current.Response.Write(strRes); //将信息写入 HTTP 响应输出流。

       HttpContext.Current.Response.Flush();//向客户端发送当前所有缓冲的输出。

       HttpContext.Current.Response.End();将当前所有缓冲的输出发送到客户端,停止该页的执行,并引发 EndRequest 事件(停止请求)