从global.asax中的Application_BeginRequest重定向到某个操作

时间:2011-08-16 10:40:32

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 asp.net-mvc-5 asp.net-mvc-2-validation

在我的网络应用程序中,我正在验证来自glabal.asax的网址。我想验证网址,如果需要,还需要重定向到某个操作。我正在使用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)
         }
     }

或者在mvc中获取请求时是否还有其他方法可以验证每个URL,并在需要时重定向到某个操作

9 个答案:

答案 0 :(得分:24)

使用以下代码进行重定向

   Response.RedirectToRoute("Default");

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

答案 1 :(得分:24)

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

您需要使用

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

答案 2 :(得分:11)

除了已经提到的方法。另一种方法是使用URLHelper,一旦出现错误,我会在场景中使用它,并且应该将用户重定向到Login页面:

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"));
    }
}

答案 3 :(得分:6)

试试这个:

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

答案 4 :(得分:3)

我这样做:

        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();

这样,您可以包装传入的请求上下文并将其重定向到其他位置,而无需重定向客户端。因此,重定向不会在global.asax中触发另一个BeginRequest。

答案 5 :(得分:0)

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

答案 6 :(得分:0)

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

    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;

        }
    }

答案 7 :(得分:0)

就我而言,我更喜欢不使用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();
        }
    }

那是我的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");
    }
}

这是我基于梅森类的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
    }
}

答案 8 :(得分:-4)

你可以试试这个:

Context.Response.Redirect();

Nt sure。