抛出HttpException总是发回HTTP 500错误?

我试图在客户端抛出一个HTTP 403错误代码。 我读过HttpException是完成这个最简单的方法,但它不适合我。 我从这样的页面中抛出异常:

throw new HttpException(403,"You must be logged in to access this resource.");

但是,这只会在CustomErrors关闭时提供标准的ASP.Net堆栈跟踪(500错误)。 如果CustomErrors打开,那么这将不会重定向到发生403错误时显示的页面。 我应该忘记HttpException,而是自己设置所有的HTTP代码? 我该如何解决?

我的Web.Config的自定义错误部分是这样的:

<customErrors mode="On" defaultRedirect="GenericErrorPage.html">
      <error statusCode="403" redirect="Forbidden.html" />
</customErrors>

而不是获取Forbidden.html,我会得到GenericErrorPage.html


你需要覆盖像这样的应用程序错误:

    protected void Application_Error()
    {
        var exception = Server.GetLastError();
        var httpException = exception as HttpException;
        Response.Clear();
        Server.ClearError();

        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;
        Response.StatusCode = 500;

        if (httpException != null)
        {
            Response.StatusCode = httpException.GetHttpCode();
            switch (Response.StatusCode)
            {
                case 403:
                    routeData.Values["action"] = "Http403";
                    break;
                case 404:
                    routeData.Values["action"] = "Http404";
                    break;
            }
        }

        IController errorsController = new ErrorsController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        errorsController.Execute(rc);
    }

然后你必须添加errorsController:

public class ErrorsController : Controller
{
    public ActionResult General(Exception exception)
    {
        ViewBag.ErrorCode = Response.StatusCode;
        ViewBag.Message = "Error Happened";

        //you should log your exception here

        return View("Index");
    }

    public ActionResult Http404()
    {
        ViewBag.ErrorCode = Response.StatusCode;
        ViewBag.Message = "Not Found";
        return View("Index");
    }

    public ActionResult Http403()
    {
        ViewBag.Message = Response.StatusCode;
        ViewBag.Message = "Forbidden";
        return View("Index");
    }

}

最后在errorsController中创建一个视图。 我在Views / Errors /中创建了一个名为index的视图。

希望这有帮助。

问候!


使用Web.config文件的元素配置/ system.web中包含的代码:

  <customErrors mode="On">
    <error statusCode="403" redirect="~/errors/Forbidden.aspx"/>
  </customErrors>

我管理它按预期工作。

您可以在这里找到一个带有示例的好教程(示例3是正确的):http://aspnetresources.com/articles/CustomErrorPages

或者您可以使用Response.Status来执行此操作:Asp Classic返回特定的http状态码


我其实已经结束了让自己漂亮的小班来解决这个问题。 它不处理所有事情,我不确定它与MVC很好,但它适用于我的使用。 基本上,不是依靠ASP.Net来输出正确的错误页面和错误代码,它会清除错误,然后执行服务器端传输并显示相应的Web.Config错误页面。 它也识别customErrors模式并作出相应的反应。

public static class CustomErrorsFixer
{
    static public void HandleErrors(HttpContext Context)
    {
        if(RunIt(Context)==false){
            return;
        }
        HttpException ex = Context.Error as HttpException;
        if(ex==null){
            try{
                ex=Context.Error.InnerException as HttpException;
            }catch{
                ex=null;
            }
        }

        if (ex != null){
            Context.Response.StatusCode = ex.GetHttpCode();
        }else{
            Context.Response.StatusCode = 500;
        }
        Context.ClearError();

        Context.Server.Transfer(GetCustomError(Context.Response.StatusCode.ToString()));
        HttpContext.Current.Response.End();
    }
    static protected string GetCustomError(string code)
    {
        CustomErrorsSection section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

        if (section != null)
        {
            CustomError page = section.Errors[code];

            if (page != null)
            {
                return page.Redirect;
            }
        }
        return section.DefaultRedirect;
    }
    static protected bool RunIt(HttpContext context){
        CustomErrorsSection section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
        switch(section.Mode){
            case CustomErrorsMode.Off:
                return false;
            case CustomErrorsMode.On:
                return true;
            case CustomErrorsMode.RemoteOnly:
                return !(context.Request.UserHostAddress=="127.0.0.1");
            default:
                return true;
        }
    }

}

然后激活它,只需向Global.asax添加一个小东西即可

    protected virtual void Application_Error (Object sender, EventArgs e)
    {
        CustomErrorsFixer.HandleErrors(Context);
    }
链接地址: http://www.djcxy.com/p/71835.html

上一篇: Throwing an HttpException always sends back HTTP 500 error?

下一篇: HTTP/2 response header field not in Pascal Case in Google Chrome