如何在asp.net 3.0应用程序中处理我的CustomAutorize属性中的错误 [英] How to handle errors in my CustomAutorize attribute in asp.net 3.0 Application

查看:142
本文介绍了如何在asp.net 3.0应用程序中处理我的CustomAutorize属性中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个asp.net MVC 3.0应用程序。我使用自己的CustomRoleProvider
和CustomErrorHandler通过覆盖默认属性。



每件事情都可以正常工作。但是,问题是异常处理。



测试应用程序时,测试人员提供了无效的数据库连接进行测试。



结果是,自定义错误处理程序不呈现错误视图,而是路由原始路径



例如:



我正在运行我的应用程序作为

 首页/索引

首先点击自定义角色提供程序获取应用程序的角色



Db连接不正确,它正在引发异常无法连接



现在,而不是路由到错误视图以及此错误消息。它是路由到家庭控制器和索引操作。

  **我的自定义错误处理程序的代码如下** 



public class CustomHandleErrorAttribute:HandleErrorAttribute //错误处理程序
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled ||!filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if(new HttpException(null,filterContext.Exception).GetHttpCode()!= 500)
{
return;
}
if(!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}

//如果请求是AJAX,返回JSON else视图。
if(filterContext.HttpContext.Request.Headers [X-Requested-With] ==XMLHttpRequest)
{
filterContext.Result = AjaxError(filterContext.Exception.Message,filterContext );
}
else
{
filterContext.ExceptionHandled = true;
var controllerName =(string)filterContext.RouteData.Values [controller];
var actionName =(string)filterContext.RouteData.Values [action];
var model = new HandleErrorInfo(filterContext.Exception,controllerName,actionName);

filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary&HandleErrorInfo&
TempData = filterContext.Controller.TempData
};
}

}
protected JsonResult AjaxError(string message,ExceptionContext filterContext)
{
if(String.IsNullOrEmpty(message))
message =处理您的请求时发生错误,请刷新页面,然后重试。
filterContext.HttpContext.Response.StatusCode =(int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
返回新的JsonResult {Data = new {ErrorMessage = message},ContentEncoding = System.Text.Encoding.UTF8,JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
}

在上面的代码中,设置了filterContext.Result 。它不会按预期方式呈现错误视图。



请更正/建议我,我在哪里出错..



更新:



public class CustomRoleProvider:RoleProvider //自定义角色提供者
{
public override string [] GetRolesForUser(string username)
{

  //从数据库获取用户的角色
}

//其他一些方法



}
这是正在产生异常的方法,因为它尝试连接到错误的连接



已更新2:



1)我正在为整个控制器使用自定义错误处理程序。



2)我需要捕获所有异常,包括Ajax错误



3)我已经包括我的自定义错误处理程序代码



4)我也使用CustomRole提供程序为整个控制器



5)这里,我是tryi通过提供错误的数据库连接来生成异常



6)我正在运行URL:Home / Index



7)在去那个URL之前,它正在使用角色提供程序类中的方法,因为我使用它作为属性



8)由于我给了错误的DB连接,它正在生成异常



9)然后,它触发自定义错误处理程序的异常方法



10 )为错误视图构建错误模型



11)但是,这里是问题。而不是渲染错误视图,它将是Home控制器的索引方法。



12)但是,我需要在这里渲染错误视图,因为它没有连接到数据库并获得角色。我想要在这里停止URL首页/索引的执行。



希望澄清问题,我正在运行。请随时询问我的详细信息/说明

解决方案

HandleError 被设计为能够注册多个过滤器(例如针对不同的例外)。一个过滤器只能处理一些特定的异常或错误情况,另一个未处理的情况可以由另一个 HandleError 来处理。我想目前正在使用标准和 [CustomHandleError] 过滤器。您可以将 Order 属性设置为整数值,该值指定从-1(最高优先级)到任何正整数值的优先级。整数值越大,过滤器的优先级越低。您可以使用订单参数,例如(请参阅这里)使您的过滤器工作。有关您可以在 MSDN文档



答案这一个文章例如提供了一些小例子的使用 属性 HandleError


I am working on an asp.net MVC 3.0 Application. I am using using my own CustomRoleProvider and CustomErrorHandler by overriding default attributes.

Every thing is working fine. But ,the problem is with the exception handling.

While testing the application , tester has given invalid DB connection to test.

The result is , Custom Error Handler is not rendering Error View , instead it is routing the original path

For ex:

I am running my application as

Home/Index

It is first hitting Custom Role Provider to fetch the roles for the application

Since , the Db Connection is not correct , it is raising exception that "Not able to Connect"

Now , Instead of routing to Error View along with this error message. It is routing to Home Controller and Index action.

**The code for my Custom Error Handler is as Follows**



public class CustomHandleErrorAttribute : HandleErrorAttribute    // Error handler 
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }
            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }
            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
            }
            else
            {
                filterContext.ExceptionHandled = true;
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

        }
        protected JsonResult AjaxError(string message, ExceptionContext filterContext)
        {
            if (String.IsNullOrEmpty(message))
                message = "Something went wrong while processing your request. Please refresh the page and try again.";
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            return new JsonResult { Data = new { ErrorMessage = message }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

In the above code , after setting up filterContext.Result . It is not rendering Error View as Expected.

Please correct/suggest me, where i am going wrong..

Updated:

public class CustomRoleProvider : RoleProvider // Custom role provider { public override string[] GetRolesForUser(string username) {

          // Fetching roles for user from database 
    }

// Some other Methods

} This is method is generating exception , since it is trying to connect to wrong connection

Updated2:

1) I am using Custom Error Handler for the entire controller.

2) I need to catch all the exceptions including Ajax Errors

3) I have included my code for Custom Error Handler Above

4) I am also using CustomRole Provider for entire controller

5) Here, I am trying to generate exception , by giving wrong database connection

6) I am running the URL : Home/Index

7) Before going to thatr URL, it is hitting the methods in Role Provider class since i am using it as a attribute

8) Since, i have gave wrong DB Connection , It is generating exception

9) Then, it fires on exception method of Custom error handler

10) Building the Error Model for the error view

11) But, here is the problem. Instead of rendering Error View , it is going to index method of the Home Controller.

12) But, i need Error View to be rendered here, because it has failed to connect to database and getting roles . I want furthuer execution of URL Home/Index to be stopped here.

Hope this clarifies the problem..i am running in to. please feel free to ask me for furthuer details/Clarification

解决方案

HandleError is designed to be able to register multiple filters (for example for different exceptions). One filter can handle only some specific exceptions or error cases and another unhandle cases can be handled by another HandleError. I suppose that currently both standard and your [CustomHandleError] filter are applied. You can set the Order property to an integer value that specifies a priority from -1 (highest priority) to any positive integer value. The greater the integer value is, the lower the priority of the filter is. You can use Order parameter for example (see here) to make your filter working before. More full description of the order you can find in the MSDN documentation.

The answer, this one and the article for example provide small examples of usage Order property of HandleError.

这篇关于如何在asp.net 3.0应用程序中处理我的CustomAutorize属性中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆