1
我有一些在多個控制器動作開始時運行的通用代碼。我想將該代碼重構爲靜態類以促進該代碼塊的重用。如何在MVC控制器的助手類中執行重定向?
代碼檢查變量,查找cookie,如果符合條件,代碼應該重定向到另一個頁面(控制器/操作)。
問題是,一切正常(包括cookie查找),但重定向不會觸發。代碼通過重定向並且重定向從不發生。
什麼是在輔助類中重定向的正確方法?
這裏是現在的代碼:
這一行是不工作:myController.HttpContext.Response.Redirect(的redirectUrl);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyProject.WebUI
{
public static class SessionValidationHelper
{
// helper class to encapsulate common routines to check for missing session data
public static void SessionIdRequired(string id, Controller myController)
{
if (id == null || id == "")
{
// check cookie
if (myController.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("cookiename"))
{
// if a session cookie was found, send to the registration recovery page
string sessionGuidCookieValue = "";
sessionGuidCookieValue = myController.ControllerContext.HttpContext.Request.Cookies["cookiename"].Value;
// check if GUID/SessionID exists in persistent cache
// send to Session Recovery
//myController.HttpContext.Response.RedirectToRoute("SessionRecovery", new { Controller = "SessionRecovery", Action = "Index", id = sessionGuidCookieValue });
string redirectURL = @"~/SessionRecovery/Index/" + sessionGuidCookieValue;
// this code isn't working
myController.HttpContext.Response.Redirect(redirectURL);
}
}
}
}
}
這是一個偉大的答案。實際上比第一個答案更完整一點,因爲var id = filterContext.RouteData.Values [「id」] as string;對我來說是一個關鍵的部分。 –