Redirect to an action from Application_BeginRequest in global.asax
Asked Answered
P

9

31

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.

  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

Phip answered 16/8, 2011 at 10:40 Comment(1)
Possible duplicate of #581228Crabwise
P
26

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 .

Phip answered 5/10, 2011 at 6:26 Comment(3)
This will create a loopCacka
@Null Pointer, please could you accept one of the other answers that works?Ussery
This causes a redirect loop to occur if used in the Application_beginRequest function.Oxygenate
E
30

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

You need to use

HttpContext.Current.RewritePath("Home/About");
Eugenioeugenius answered 11/9, 2014 at 10:49 Comment(0)
P
26

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 .

Phip answered 5/10, 2011 at 6:26 Comment(3)
This will create a loopCacka
@Null Pointer, please could you accept one of the other answers that works?Ussery
This causes a redirect loop to occur if used in the Application_beginRequest function.Oxygenate
J
14

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 :

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"));
    }
}
Jowers answered 12/5, 2016 at 0:25 Comment(5)
That causes another request. Which in turns makes another,. Which makes another. And so on when you're in the application_begin request function.Oxygenate
@RichardBarker This code is not located in application_begin request!!!! I put it in Application_PostAuthenticateRequest an in the catch block in cas error happendJowers
My apologies. The question showed BeginRequest. May I suggest you update your answer to show that and explain why you did it?Oxygenate
That's a bit better, but I created a short complete code example from your update. That will help future stackers by making it easier to understand and also utilize. I believe this to be the best solution for the issue described in the OP - it will avoid the loop issue but first it needs one more check for the current request being for the login action.Oxygenate
I like this as it generates the MVC route from the helper and will inherently handle a change to the routing. I'm never comfortable hard coding MVC routes as strings!Terpstra
T
6

Try this:

HttpContext.Current.Response.Redirect("...");
Timbal answered 16/8, 2011 at 16:43 Comment(0)
G
5

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.

Grout answered 2/6, 2015 at 14:3 Comment(0)
W
0
 Response.RedirectToRoute(
                                new RouteValueDictionary {
                                    { "Controller", "Home" },
                                    { "Action", "TimeoutRedirect" }}  );
Wilks answered 23/1, 2015 at 9:0 Comment(1)
This will cause another request; which will cause another request. Which causes another request. Which creates another. Until it errors out completely.Oxygenate
S
0

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.

    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;

        }
    }
Sequacious answered 23/5, 2016 at 15:53 Comment(0)
C
0

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

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

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

//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
    }
}
Competitive answered 12/11, 2019 at 12:19 Comment(0)
C
-4

You can try with this:

Context.Response.Redirect(); 

Nt sure.

Crabwise answered 16/8, 2011 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.