【问题标题】:Getting the original requested URL before custom error handling Redirect in ASP.NET MVC4在 ASP.NET MVC4 中的自定义错误处理重定向之前获取原始请求的 URL
【发布时间】:2016-05-26 10:39:09
【问题描述】:

我在 ASP.NET MVC4 中使用自定义错误处理来在捕获 404 状态时重定向到自定义错误页面。

代码如下


Web.Config

<customErrors mode="On">
  <error statusCode="404" redirect="~/Error/NotFoundError"/>   
</customErrors>

错误控制器

    public ActionResult NotFoundError()
    {
        string originalUrl = Request.Url.AbsolutePath;

        Errormodel model = new Errormodel();
        model.URL = originalUrl ;

        return View(model);
    }

请注意,我使用 Request 对象上的 Request.Url.AbsolutePath 属性来获取 URL。

问题是我想在重定向之前获取目标的原始 URL 以便在我的视图中显示它,而不是获取到自定义错误页面的 url。

视图中的示例

您请求的 http://testproject/test 未找到。

如何获取原始目标 URL 而不是新的自定义错误页面 URL?

【问题讨论】:

  • 你试过Request.UrlReferrer.AbsolutePath吗?
  • Request.UrlReferrer 似乎为我返回 null。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

你可以检查这个答案 ASP.NET MVC 404 Error Handling

基本上它使用函数 Application_EndRequest 事件在执行新操作之前添加任何信息

public class MvcApplication : HttpApplication
{
    protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 404)
        {
            Response.Clear();

            var rd = new RouteData();
            rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
            rd.Values["controller"] = "Errors";
            rd.Values["action"] = "NotFound";

            IController c = new ErrorsController();
            c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2013-08-17
    • 2011-08-29
    相关资源
    最近更新 更多