【问题标题】:How can a URL be left as is but still render an error view?如何保持 URL 不变但仍呈现错误视图?
【发布时间】:2013-10-18 22:41:40
【问题描述】:

我正在为“Gone”请求(410 代码)创建一个控制器和视图,我这样做的方法是将 customError 状态代码 410 添加到我的 Web.config 中。

这会正确处理异常并呈现视图,但响应 URL 是

http://www.mysite.com/Error/Gone?aspxerrorpath=/requested-page

我希望保留原始 URL,同时仍显示 Gone View,换句话说,保持 url 不变:“http://www.mysite.com/requested-page

知道我可以从哪里开始吗?

【问题讨论】:

  • 只是为了确定。您说“我的 Web.config 的 customError 状态代码 10”这应该是 410 对吗?如果是,您能否更新问题?
  • 我认为你需要这个别名。看这里stackoverflow.com/questions/9853429/…
  • 谢谢 Raj,我已经更新了问题。非常感谢马特,我会研究别名。

标签: asp.net asp.net-mvc url http-status-code-410


【解决方案1】:

要保留原始 URL,您可以使用 here 描述的路线并在 global.asax 中明确处理错误,而不是使用 web.config customerrors 或 httperrors 部分(仍然可以配置为回退)但更改 使用 HttpContext.Server.TransferRequest(path, true) 的链接网站示例上的 IHttpHandler.ProcessRequest 部分。 我已经在我的一个项目中实现了这样的 Application_Error 事件:

protected void Application_Error()
{
    Exception error = Server.GetLastError();
    var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;

    if (!Context.IsDebuggingEnabled
        && code != 404)
    {
        // persist error to error log db
        //Log.Logger.Error("unhandled exception: ", exception);
    }

    if (WebConfigurationManager.AppSettings["EnableCustomExceptionPage"].Equals("false"))
    {
        return;
    }

    Response.Clear();
    Server.ClearError();

    string path = this.Request.Path;
    string action;
    switch (code)
    {
        case 401:
            action = "Unauthorized";
            break;
        case 403:
            action = "Forbidden";
            break;
        case 404:
            action = "NotFound";
            break;
        default:
            action = "Generic";
            break;
    }
    string newPath = string.Format("~/Error/{0}?source={1}&message={2}", action, path,
                                   HttpUtility.UrlEncode(error.Message));
    Context.Server.TransferRequest(newPath, true);
}

在内部,它将请求转移到一个新路径,即由 ErrorController 处理,如上面描述的示例中的操作可能如下所示:

public ViewResult Generic(string source, string message)
{
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = 500;
    ViewBag.Source = source;
    ViewBag.Message = HttpUtility.UrlDecode(message);
    return View();
}

public ViewResult NotFound(string source, string message)
{
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = 404;
    ViewBag.Source = source;
    ViewBag.Message = HttpUtility.UrlDecode(message);
    return View();
}

...

TrySkipIisCustomErrors = true 阻止 IIS 重定向到默认的自定义错误页面。 您可以在 Application_Error 覆盖方法中以不同的方式处理抛出的异常(如业务/服务层中抛出的特殊异常)而不是 HttpException。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多