C#创建使用一般处理程序.ashx

来源:互联网 发布:淘宝上下架时间设置 编辑:程序博客网 时间:2024/05/29 23:44


<% @ webhandler language="C#" class="testHandler" %>

  using System;

  using System.Web;

  public class testHandler : IHttpHandler

  {

   public bool IsReusable
 
   { get { return true; } }
 
   public void ProcessRequest(HttpContext ctx)
 
   {
  ctx.Response.ContentType = "text/plain";  //text/html
  ctx.Response.Charset  = "utf-8";  
  ctx.Response.StatusCode = 200;
 
  // ctx.Request.QueryString["abc"];
  string title = ctx.Request.Form["title"];
  ctx.Response.Write(title);
  ctx.Response.Write(" hello");

    }

  }



---- 发送邮件 Demo ----

<%@ WebHandler Language="C#" Class="MailHandler.GenericMailHandler" %>

using System;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace MailHandler{

    public class GenericMailHandler : IHttpHandler {
        
        public void ProcessRequest (HttpContext ctx) {
            ctx.Response.ContentType = "text/plain";
            ctx.Response.Charset = "utf-8";
            
            //string _mailServer = "mail.smtp2go.com";
            string _mailServer = ctx.Request.Form["mailServer"].ToString();
            int _port = Convert.ToInt32(ctx.Request.Form["port"].ToString());
            string _username = ctx.Request.Form["username"].ToString();
            string _password = ctx.Request.Form["password"].ToString();
            string _fromMail = ctx.Request.Form["fromMail"].ToString();
            string _toMail = ctx.Request.Form["toMail"].ToString();
            string _subject = ctx.Request.Form["subject"].ToString();
            string _htmlbody = ctx.Request.Form["htmlbody"].ToString();
            if (string.IsNullOrEmpty(_mailServer))
                _mailServer = "mail.smtp2go.com";
            if (_port==null || _port == 0)
                _port = 25;

            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient client = new SmtpClient(_mailServer, _port);                  //Port 8025, 587 and 25 can also be used.
                client.Credentials = new NetworkCredential(_username, _password);        //use authication code
                client.EnableSsl = true;
                mail.From = new MailAddress(_fromMail);
                mail.To.Add(_toMail);
                mail.Subject = _subject;
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(_htmlbody, UTF8Encoding.UTF8, "text/html");
                mail.AlternateViews.Add(htmlView);
                client.Send(mail);
                ctx.Response.Write("Send");

            }
            catch (Exception ex)
            {
                ctx.Response.Write(ex.Message);
            }
        }

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




0 0
原创粉丝点击