我正在使用我的ASP.NET MVC 2项目.我创建异常过滤器来捕获用户没有权限查看某些操作时发生的未经授权的访问异常.
[CustomError(typeof(UnauthorizedAccessException),"Error","UnauthorizedAccess")] public class MyController : BaseController { }
抛出异常之后,我的过滤器将转移到以下方法的配置控制器/操作.
public ActionResult UnauthorizedAccess(ExceptionContext context) { Response.StatusCode = CustomHttpStatusCode.UnauthorizedUser; return View(model); }
最后,在ASP.NET应用程序结束此请求之前,将调用位于Global.ascx中的以下方法将自定义HTTP状态代码更改为HTTP状态401(未经授权的访问).
public void Application_EndRequest(object sender,EventArgs e) { if (Response.StatusCode == CustomHttpStatusCode.UnauthorizedUser) { Response.StatusCode = 401; } }
一切都在我的机器上工作正常(IIS 7.5).但它在我的部署网站上不起作用.它仍然返回纯文本“您没有权限查看此目录或页面”.而不是我的自定义错误页面.
PS.以下配置是我当前这个case的web.config.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.web> <customErrors mode="On"></customErrors> </system.web> <system.webServer> <httpErrors errorMode="Custom"> <remove statusCode="502" subStatusCode="-1" /> <remove statusCode="501" subStatusCode="-1" /> <remove statusCode="500" subStatusCode="-1" /> <remove statusCode="412" subStatusCode="-1" /> <remove statusCode="406" subStatusCode="-1" /> <remove statusCode="405" subStatusCode="-1" /> <remove statusCode="404" subStatusCode="-1" /> <remove statusCode="403" subStatusCode="-1" /> <remove statusCode="401" subStatusCode="-1" /> </httpErrors> </system.webServer> </configuration>
解决方法
我刚刚找到了解决这个问题的方便.我只是添加新的设置到web.config文件,如下面的代码.一切都在我的部署网站上运行正常.
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <httpErrors errorMode="Custom" existingResponse="PassThrough"> <remove statusCode="502" subStatusCode="-1" /> <remove statusCode="501" subStatusCode="-1" /> <remove statusCode="500" subStatusCode="-1" /> <remove statusCode="412" subStatusCode="-1" /> <remove statusCode="406" subStatusCode="-1" /> <remove statusCode="405" subStatusCode="-1" /> <remove statusCode="404" subStatusCode="-1" /> <remove statusCode="403" subStatusCode="-1" /> <remove statusCode="401" subStatusCode="-1" /> </httpErrors> </system.webServer> </configuration>
欲了解更多信息:HttpErrorsSection Class