gpt4 book ai didi

c# - 如何处理 HTTPHandler 中的异常?

转载 作者:可可西里 更新时间:2023-11-01 16:38:13 26 4
gpt4 key购买 nike

我有使用 HTML 和 asp.net HTTP 处理程序的邮件发送程序。

这是我的 html 页面,它向 .ashx 页面发送请求

<html>
<form id="ContactForm" action="EmailHandler.ashx" method="post">
Name: <input class="input" type="text" id="contactname" name="contactname" autocomplete="on" required/>
Email <input class="input" type="email" id="contactemail" name="contactemail" autocomplete="on" required />
Comments<textarea cols="50" rows="5" id="contactmessage" name="contactmessage" required></textarea>

<input type="submit" id="emailsubmit" name="emailsubmit" value="Send" />
</form>
</html>

这是我的 httphandler (EmailHandler.ashx)

public class EmailHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string name = context.Request.Form["contactname"];
string email = context.Request.Form["contactemail"];
string content = context.Request.Form["contactmessage"];
try
{
SendEmail(name, email, content);

}
catch (Exception)
{
*******
}
}

public bool IsReusable { get { return false; } }

public void SendEmail(string name, string emailid, string emailcontent)
{
SmtpClient serverobj = new SmtpClient();
MailMessage msgobj = new MailMessage();

msgobj.To.Add("abc@ymail.com");
msgobj.Subject = "Its From Guest";
msgobj.Body = emailcontent;
msgobj.IsBodyHtml = true;
msgobj.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
serverobj.Send(msgobj);

}

现在如何处理来自此处理程序的响应。

  1. 如果电子邮件发送成功,如何将成功消息反射(reflect)到同一个 html 页面?

  2. 如果出现异常如何处理异常或异常信息?

最佳答案

您可以使用 context 将值直接写回调用页面,如下所示:

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string name = context.Request.Form["contactname"];
string email = context.Request.Form["contactemail"];
string content = context.Request.Form["contactmessage"];
try
{
SendEmail(name, email, content);
}
catch (Exception ex)
{
// Write exception message to user
// You can include some of the exception detail via the ex object,
// but be careful how much information you divulge to the user
context.Response.Write("There was a problem sending the email.");
}

// Email was sent successfully
context.Response.Write("Email sent successfully.");
}

关于c# - 如何处理 HTTPHandler 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com