Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to an action from Application_BeginRequest in global.asax

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

like image 942
Null Pointer Avatar asked Aug 16 '11 10:08

Null Pointer


3 Answers

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"); 
like image 153
Afazal Avatar answered Sep 24 '22 09:09

Afazal


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 .

like image 25
Null Pointer Avatar answered Sep 24 '22 09:09

Null Pointer


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"));
    }
}
like image 31
Nelly Sattari Avatar answered Sep 22 '22 09:09

Nelly Sattari