How to simulate Server.Transfer in ASP.NET MVC?

后端 未结 14 1429
死守一世寂寞
死守一世寂寞 2020-11-22 12:00

In ASP.NET MVC you can return a redirect ActionResult quite easily :

 return RedirectToAction(\"Index\");

 or

 return RedirectToRoute(new { controller = \"         


        
14条回答
  •  醉酒成梦
    2020-11-22 12:44

    Edit: Updated to be compatible with ASP.NET MVC 3

    Provided you are using IIS7 the following modification seems to work for ASP.NET MVC 3. Thanks to @nitin and @andy for pointing out the original code didn't work.

    Edit 4/11/2011: TempData breaks with Server.TransferRequest as of MVC 3 RTM

    Modified the code below to throw an exception - but no other solution at this time.


    Here's my modification based upon Markus's modifed version of Stan's original post. I added an additional constructor to take a Route Value dictionary - and renamed it MVCTransferResult to avoid confusion that it might just be a redirect.

    I can now do the following for a redirect:

    return new MVCTransferResult(new {controller = "home", action = "something" });
    

    My modified class :

    public class MVCTransferResult : RedirectResult
    {
        public MVCTransferResult(string url)
            : base(url)
        {
        }
    
        public MVCTransferResult(object routeValues):base(GetRouteURL(routeValues))
        {
        }
    
        private static string GetRouteURL(object routeValues)
        {
            UrlHelper url = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()), RouteTable.Routes);
            return url.RouteUrl(routeValues);
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = HttpContext.Current;
    
            // ASP.NET MVC 3.0
            if (context.Controller.TempData != null && 
                context.Controller.TempData.Count() > 0)
            {
                throw new ApplicationException("TempData won't work with Server.TransferRequest!");
            }
    
            httpContext.Server.TransferRequest(Url, true); // change to false to pass query string parameters if you have already processed them
    
            // ASP.NET MVC 2.0
            //httpContext.RewritePath(Url, false);
            //IHttpHandler httpHandler = new MvcHttpHandler();
            //httpHandler.ProcessRequest(HttpContext.Current);
        }
    }
    

提交回复
热议问题