简体   繁体   English

在自定义错误处理之前获取原始请求的URL在ASP.NET MVC4中重定向

[英]Getting the original requested URL before custom error handling Redirect in ASP.NET MVC4

I am using custom error handling in ASP.NET MVC4 for redirecting to a custom error page when a 404 status is caught. 我在ASP.NET MVC4中使用自定义错误处理,以在捕获到404状态时重定向到自定义错误页面。

The code is as follows 代码如下


Web.Config Web配置

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

Error Controller 错误控制器

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

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

        return View(model);
    }

Notice that I use the Request.Url.AbsolutePath property on the Request object to get the URL. 注意,我在Request对象上使用Request.Url.AbsolutePath属性来获取URL。

The problem is that I would like to get the original URL that I targeted before the redirect in order to show it in my view, and instead I get the url to the custom error page. 问题是,我想获得重定向之前定位的原始URL以便在视图中显示它,而是将URL获取到自定义错误页面。

Example in View 视图中的示例

You requested http://testproject/test which was not found. 您请求的http:// testproject / test未找到。

How could I get the original target URL as opposed to the new custom error page URL? 如何获得原始目标URL而不是新的自定义错误页面URL?

You can check this answer ASP.NET MVC 404 Error Handling 您可以检查此答案ASP.NET MVC 404错误处理

Basicaly it using function Application_EndRequest event to add any information before go to new action 基本上,它使用功能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));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM