在Asp.net MVC 3 Web开发中,我们会大量使用各种ajax请求,针对ajax请求如何结何server端如何做异常处理呢?我们可以扩展ActionFilterAttribute,实现一个Ajax异常处理特性。假设您是使用JQuery脚本开发来实现Ajax,看代码:
#region AjaxExceptionAttribute
/// <summary>
/// Ajax Exception Handle Attribute
/// </summary>
5: [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
class AjaxExceptionAttribute : ActionFilterAttribute, IExceptionFilter
7: {
/// <summary>
/// Called when an exception occurs.
/// </summary>
void OnException(ExceptionContext filterContext)
13: {
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
16:
17: filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
18:
//Let the system know that the exception has been handled
true;
21: }
22:
/// <summary>
/// Ajaxes the error.
/// </summary>
/// <returns>JsonResult</returns>
string message, ExceptionContext filterContext)
30: {
//If message is null or empty, then fill with generic message
if (String.IsNullOrEmpty(message))
;
34:
//Set the response status code to 500
int)HttpStatusCode.InternalServerError;
37:
//Needed for IIS7.0
true;
40:
new JsonResult
42: {
//can extend more properties
new AjaxExceptionModel () { ErrorMessage = message },
45: ContentEncoding = System.Text.Encoding.UTF8,
46: JsonRequestBehavior = JsonRequestBehavior.DenyGet
47: };
48: }
49: }
#endregion
51:
/// <summary>
/// AjaxExceptionModel
/// </summary>
class AjaxExceptionModel
56: {
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
string ErrorMessage { get; set; }
64: }