我創建了一個檢查HTTP標頭的動作結果,如果返回某個標頭值,那麼我想將一個布爾值存儲在會話變量中。然後,我想要在局部視圖中使用該會話變量以確定是否應顯示某個HTML。ASP.NET MVC:將數據從操作過濾器傳遞到視圖
如何將我的操作篩選器中的會話變量傳遞給我的部分視圖?
行爲過濾(內BaseController.cs):
public class AuthorizationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
string url = "http://www.website.com";
bool retry = false;
int retries = 0;
int maxRetries = 2;
bool authorized = true;
bool paymentReceived = true;
do
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// If not authorized, redirect to login page
if (response.Headers["key"] == "1")
{
authorized = false;
filterContext.HttpContext.Session["authorized"] = authorized;
filterContext.Result = new RedirectResult("https://www.website.com");
}
response.Close();
}
catch (WebException we)
{
System.Diagnostics.Debug.Write(we.Message + "\n");
retry = true;
retries++;
}
}
while (retry == true && retries < maxRetries);
}
}
管窺(目前):
<ul class="navigation">
<li><a href="/">Nav 1</a></li>
<li><a href="/">Nav 2</a></li>
@if (Model.Authorized != null)
{
if (Model.Authorized == true)
{
<li><a href="/">Nav 3</a></li>
}
}
</ul>
我最初只是想通過會話變量的部分視圖直接從BaseController像這樣:
@if (Session["authorized"] == true)
但我繼續從它得到NullReferenceException
。然後我看了四周,看見的數據應該從控制器通過一個模型的視圖進行傳遞,所以我不喜歡的東西下面:
各個控制器:
public class ControllerModel : BaseControllerModel
{
public bool Authorized { get; set; }
}
public ActionResult Authorized()
{
ControllerModel model = new ControllerModel();
model.Authorized = (bool)HttpContext.Session["authorized"];
return View(model);
}
現在,Session變量在那裏,但它總是返回false(我假設它只是返回默認值)。
在這一點上我看到兩個問題:
我創建在兩個不同的位置單獨會話變量,在基本控制器,並在每個單獨的控制器。部分視圖是從單獨的控制器中提取數據,那麼如何才能讓局部視圖從基礎控制器中獲取數據?
如果我應該先將數據傳遞給模型,我應該在BaseController中創建一個動作方法並使用BaseControllerModel(見下文)?這聽起來像是一個可怕的想法,但我想以某種方式制定一種適用於所有控制器的通用方法,因爲局部視圖存在於每個視圖中。
在基本控制器:
public ActionResult Authorized()
{
BaseControllerModel model = new BaseControllerModel();
model.Authorized = (bool)HttpContext.Items["authorized"];
return View(model);
}
在基本控制器型號:
public bool Authorized { get; set; }
如果刪除authorized = false,會話變量是否仍然爲false? – scheien
@scheien是的。仍然是假的。我認爲缺少的一點是我沒有在每個單獨的控制器中將基本控制器操作過濾器與我的操作方法相連接。也許? – Keven
我想你會需要用過濾器裝飾適當的方法是。 – scheien