Example: Receive HTTP Post via ASP.Net Generic Handler

10 篇文章 0 订阅

假设我们要提供一个小小的服务,采用HTTP协议进行通讯,客户端 POST 一些数据到服务器上。客户端不一定是PC,更不一定会按照一个Web Form的格式来提交数据,它可能是一个运行在PC上的Desktop Application,也可能是一个移动设备。

 

服务器端接收这样的请求极其简单,下面寥寥数行代码即可实现:

在Web站点中新建一个Generic Handler(*.ashx),代码如下:

<%@ WebHandler Language="C#" Class="Echo" %>

using System;
using System.Web;
using System.IO;

public class Echo : IHttpHandler
{
    private System.Text.Encoding DefaultEncoding = System.Text.Encoding.UTF8;
    
    public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = DefaultEncoding;

        Stream inputStream = context.Request.InputStream;
        using (StreamReader reader = new StreamReader(inputStream, DefaultEncoding))
        {
            string requestContent = reader.ReadToEnd();
            string responseContent = string.Format("Received: {0} <== END", requestContent);
            
            context.Response.Write(responseContent);
        }
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

然后我们写一个简单的客户端来测试它。在这个客户端里我们实现了一个类HttpClient来进行HTTP POST操作:

// -----------------------------------------------------------------------
// <copyright file="HttpClient.cs" author="Yaping Xin">
// Http protocol client.
// </copyright>
// -----------------------------------------------------------------------

namespace ConsoleClient
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    /// <summary>
    /// Http protocol client.
    /// </summary>
    public class HttpClient
    {
        /// <summary>
        /// Post data to specific url and get response content.
        /// </summary>
        /// <param name="url">the url to post</param>
        /// <param name="postData">post data</param>
        /// <returns>response content</returns>
        public string Post(string url, string postData)
        {
            Uri uri = new Uri(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            Encoding encoding = Encoding.UTF8;
            byte[] bytes = encoding.GetBytes(postData);

            request.ContentLength = bytes.Length;

            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(bytes, 0, bytes.Length);
                writer.Close();
            }

            return this.ReadResponse(request);;
        }

        /// <summary>
        /// Read response content from http request result.
        /// </summary>
        /// <param name="request">http request object</param>
        /// <returns>response content.</returns>
        private string ReadResponse(HttpWebRequest request)
        {
            string result = string.Empty;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                        reader.Close();
                    }
                }
            }

            return result;
        }
    }
}



然后我们这样就能得到HTTP POST的返回:

// Replace the string content with your actual address please.
string defaultUrl = "http://ServerName:8081/WebPath/AnyService.ashx";

HttpClient client = new HttpClient();
string response = client.Post(defaultUrl, @"abc 123! 测试 @");

Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine(response);


假设Client与Server两端都约定好采取某个格式对数据进行序列化与反序列化,例如都采用Json,客户端把对象通过Json封装后Post给Server,Server再采用Json将对象从Json字符串中解析出来,这样进行数据传递是便利的。再假设我们要压缩传送出的数据量,那么可以进行gzip压缩与解压。又假设我们要考虑安全性,那么我们可以在对象的结构中添加security token进行认证,以及采用某种加密算法对字符串进行加密与解密。怎么发挥就看您具体的应用了,构建一个属于您自己的轻量的service易如反掌。


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值