开发者

Redirect to an action from Application_BeginRequest in global.asax

开发者 https://www.devze.com 2023-03-28 15:15 出处:网络
In my web application I am validatingthe 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 reques开发者_如

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 reques开发者_如何转开发t 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


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


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 .


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


Try this:

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


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.


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


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;

        }
    }


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
    }
}


You can try with this:

Context.Response.Redirect(); 

Nt sure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号