获取HandleError属性中的服务器文件夹路径和Request.IsAjaxRequest()

时间:2014-01-28 05:49:29

标签: asp.net-mvc-4 exception-handling

我正在尝试在ASP.Net MVC4应用程序中扩展HandleErrorAttribute。但问题是我无法获得〜/ App_Data的路径。另一个问题是我想定义它是否是AjaxRequest。我的代码如下 -

using sCommonLib;
using System;
using System.Web;
using System.Web.Mvc;
using sCommonLib;

public class HandleErrors:System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {       
        if (filterContext.ExceptionHandled)
        {
            return;
        }
        else
        {
            var path = HttpContext.Server.MapPath("~/App_Data"); //need help here              
            string actionName = filterContext.RouteData.Values["action"].ToString();
            Type controllerType = filterContext.Controller.GetType();
            var method = controllerType.GetMethod(actionName);
            var returnType = method.ReturnType;

            if (returnType.Equals(typeof(JsonResult)))
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "Some error."
                };
            }

            if (returnType.Equals(typeof(ActionResult))
            || (returnType).IsSubclassOf(typeof(ActionResult)))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "URL to the errror page"
                };
            }
        }

        filterContext.ExceptionHandled = true;
    }
}

有任何线索吗?

1 个答案:

答案 0 :(得分:0)

试试这个

if(Request.IsAjaxRequest())
{
    var path = HSystem.Web.HttpContext.Current.Server.MapPath(@"~/App_Data"); // here              
    string actionName = filterContext.RouteData.Values["action"].ToString();
    Type controllerType = filterContext.Controller.GetType();
    var method = controllerType.GetMethod(actionName);
    var returnType = method.ReturnType;

    if (returnType.Equals(typeof(JsonResult)))
    {
        filterContext.Result = new JsonResult()
        {
            Data = "Some error."
        };
    }

    if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult)))
    {
        filterContext.Result = new ViewResult
            {
                ViewName = "URL to the errror page"
            };
    }
}

希望有所帮助:)