我還是有點糊塗了所有不同的解決方案在那裏,以及如何屬性可以互相干擾,但我用這個解決方案去:
public class LogErrorsAttribute: FilterAttribute, IExceptionFilter
{
#region IExceptionFilter Members
void IExceptionFilter.OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.Exception != null)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
string loggerName = string.Format("{0}Controller.{1}", controller, action);
log4net.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception);
}
}
#endregion
}
我還是用下,[HandleError]屬性正如原來的問題所解釋的那樣,我只是用一個[LogErrors]屬性來修飾每個控制器。
這對我有用,因爲它將錯誤記錄保存在一個地方,並且不會導致重複記錄多次異常(如果我擴展[HandleError]並在多個位置使用該屬性,就會發生這種情況)。
我不認爲這將有可能同時異常日誌記錄和錯誤處理成一個atrribute或類結合,沒有它變得非常繁瑣和複雜,或影響使用[的HandleError]
,但這適用於我,因爲我只用一次[LogErrors]屬性裝飾每個控制器,並用[HandleError]裝飾控制器和動作,而不是互相干擾。
更新:
這裏是如何使用它的一個例子:
[LogErrors(Order = 0)]
[HandleError(Order = 99)]
public class ContactController : Controller
{
public ActionResult Index()
{
return View(Views.Index);
}
public ActionResult Directions()
{
return View(Views.Directions);
}
public ActionResult ContactForm()
{
FormContactMessage formContactMessage = new FormContactMessage();
return View(Views.ContactForm,formContactMessage);
}
[HandleError(ExceptionType = typeof(SmtpException), View = "MessageFailed", Order = 1)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactForm(FormContactMessage formContactMessage)
{
if (ModelState.IsValid)
{
if (formContactMessage.IsValid)
{
SmtpClient client = new SmtpClient();
MailAddress recipientAddress = new MailAddress(Properties.Settings.Default.ContactFormRecipientEmailAddress);
MailAddress senderAddress = new MailAddress(Properties.Settings.Default.ContactFormSenderEmailAddress);
MailMessage mailMessage = formContactMessage.ToMailMessage(recipientAddress, senderAddress);
client.Send(mailMessage);
return View("MessageSent");
}
else
{
ModelState.AddRuleViolations(formContactMessage.GetRuleViolations());
}
}
return View(Views.ContactForm, formContactMessage);
}
private static class Views
{
public static string Index { get { return "Index"; } }
public static string Directions { get { return "Directions"; } }
public static string ContactForm { get { return "ContactForm"; } }
}
}
在上面的代碼,在ContactForm
行動超載SmtpExceptions在一個非常特殊的方式處理 - 用戶與查看失敗的發送消息相關的ViewPage,在這種情況下,它被稱爲「MessageFailed」。所有其他異常都由[HandleError]的默認行爲處理。另請注意,首先發生錯誤記錄,然後處理錯誤。這是由以下指示:
[LogErrors(Order = 0)]
[HandleError(Order = 99)]
更新:
,有一種替代解決這個,有一個非常好的explanantion。我建議通讀它以更好地理解所涉及的問題。
ASP.NET MVC HandleError Attribute, Custom Error Pages and Logging Exceptions (感謝下面的Scott Shepherd,誰在下面的答案中提供了鏈接)。
不錯,非常感謝,我會用這個。 – Kezzer 2009-09-18 10:48:29