asp.net-mvc 重定向到 global.asax 中来自 Application_BeginRequest 的操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7076901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:24:44  来源:igfitidea点击:

Redirect to an action from Application_BeginRequest in global.asax

asp.net-mvcasp.net-mvc-4asp.net-mvc-3asp.net-mvc-5asp.net-mvc-2-validation

提问by Null Pointer

In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application_BeginRequest to catch the request event.

在我的 Web 应用程序中,我正在验证来自 glabal.asax 的 url。我想验证 url,如果需要,需要重定向到一个操作。我正在使用 Application_BeginRequest 来捕获请求事件。

  protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // If the product is not registered then
        // redirect the user to product registraion page.
        if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
        {
             //HOW TO REDIRECT TO ACTION (action=register,controller=product)
         }
     }

Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed

或者有没有其他方法可以在获取 MVC 中的请求时验证每个 url 并在需要时重定向到操作

采纳答案by Null Pointer

Use the below code for redirection

使用以下代码进行重定向

   Response.RedirectToRoute("Default");

"Default" is route name. If you want to redirect to any action,just create a route and use that route name .

“默认”是路由名称。如果您想重定向到任何操作,只需创建一个路由并使用该路由名称。

回答by Afazal

All above will not work you will be in the loop of executing the method Application_BeginRequest.

以上所有都不起作用,您将处于执行该方法的循环中Application_BeginRequest

You need to use

你需要使用

HttpContext.Current.RewritePath("Home/About");

回答by Nelly Sattari

Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :

除了已经提到的方法。另一种方法是使用 URLHelper,一旦发生错误,我在一个场景中使用了它,用户应该被重定向到登录页面:

public void Application_PostAuthenticateRequest(object sender, EventArgs e){
    try{
         if(!Request.IsAuthenticated){
            throw  new InvalidCredentialException("The user is not authenticated.");
        }
    } catch(InvalidCredentialException e){
        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        Response.Redirect(urlHelper.Action("Login", "Account"));
    }
}

回答by James Johnson

Try this:

尝试这个:

HttpContext.Current.Response.Redirect("...");

回答by Tim Geerts

I do it like this:

我这样做:

        HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Home");
        routeData.Values.Add("action", "FirstVisit");

        IController controller = new HomeController();

        RequestContext requestContext = new RequestContext(contextWrapper, routeData);

        controller.Execute(requestContext);
        Response.End();

this way you wrap the incoming request context and redirect it to somewhere else without redirecting the client. So the redirect won't trigger another BeginRequest in the global.asax.

通过这种方式,您可以包装传入的请求上下文并将其重定向到其他地方,而无需重定向客户端。所以重定向不会触发 global.asax 中的另一个 BeginRequest。

回答by J. Horn

I had an old web forms application I had to convert to MVC 5 and one of the requirements was supporting possible {old_form}.aspx links. In Global.asax Application_BeginRequest I set up a switch statement to handle old pages to redirect to the new ones and to avoid the possible undesired looping to the home/default route check for ".aspx" in the request's raw URL.

我有一个旧的 Web 表单应用程序,我必须转换为 MVC 5,其中一项要求是支持可能的 {old_form}.aspx 链接。在 Global.asax Application_BeginRequest 中,我设置了一个 switch 语句来处理旧页面以重定向到新页面,并避免可能不需要的循环到请求的原始 URL 中的“.aspx”的主/默认路由检查。

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        OldPageToNewPageRoutes();
    }

    /// <summary>
    /// Provide redirects to new view in case someone has outdated link to .aspx pages
    /// </summary>
    private void OldPageToNewPageRoutes()
    {
        // Ignore if not Web Form:
        if (!Request.RawUrl.ToLower().Contains(".aspx"))
            return;

        // Clean up any ending slasshes to get to the old web forms file name in switch's last index of "/":
        var removeTrailingSlash = VirtualPathUtility.RemoveTrailingSlash(Request.RawUrl);
        var sFullPath = !string.IsNullOrEmpty(removeTrailingSlash)
            ? removeTrailingSlash.ToLower()
            : Request.RawUrl.ToLower();
        var sSlashPath = sFullPath;

        switch (sSlashPath.Split(Convert.ToChar("/")).Last().ToLower())
        {
            case "default.aspx":
                Response.RedirectToRoute(
                    new RouteValueDictionary
                    {
                        {"Controller", "Home"},
                        {"Action", "Index"}
                    });
                break;
            default:
                // Redirect to 404:
                Response.RedirectToRoute(
                    new RouteValueDictionary
                    {
                        {"Controller", "Error"},
                        {"Action", "NotFound"}
                    });
                break;

        }
    }

回答by danteMesquita

In my case, i prefer not use Web.config. Then i created code above in Global.asax file:

就我而言,我不喜欢使用 Web.config。然后我在 Global.asax 文件中创建了上面的代码:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        //Not Found (When user digit unexisting url)
        if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
        {
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "NotFound");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
        else //Unhandled Errors from aplication
        {
            ErrorLogService.LogError(ex);
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
    }

And thtat is my ErrorController.cs

那是我的 ErrorController.cs

public class ErrorController : Controller
{
    // GET: Error
    public ViewResult Index()
    {
        Response.StatusCode = 500;
        Exception ex = Server.GetLastError();
        return View("~/Views/Shared/SAAS/Error.cshtml", ex);
    }

    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("~/Views/Shared/SAAS/NotFound.cshtml");
    }
}

And that is my ErrorLogService.cs based on mason class

那是我基于 mason 类的 ErrorLogService.cs

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Do what you want here, save log in database, send email to police station
    }
}

回答by evgnib

 Response.RedirectToRoute(
                                new RouteValueDictionary {
                                    { "Controller", "Home" },
                                    { "Action", "TimeoutRedirect" }}  );

回答by Baz1nga

You can try with this:

你可以试试这个:

Context.Response.Redirect();?

Context.Response.Redirect();?

Nt sure.

不确定。