簡體   English   中英

ASP.NET MVC 5(非 MVC 核心)TempData 在 Azure AppService 環境之一中不起作用並返回 null 值

[英]ASP.NET MVC 5 (Not MVC Core) TempData is not working in one of the Azure AppService Environment and returns null value

問題陳述:ASP.NET MVC TempData在 Azure AppService 之一中不起作用(例如:- 我說為 UAT 環境創建的 App Service)。 RedirectToAction發生時,獲取TempData值將返回 null。

注意:我們有不同的環境應用服務。 這意味着 DEV、SIT、UAT 環境的各個階段。 令人驚訝的是,該功能在 DEV 和 SIT 環境中用於相同的構建。 但不在 UAT 應用服務中。

這是代碼:

public ActionResult Index()
{
    TempData["Message"] = MessageModel;
    return RedirectToAction("About");
}

public ActionResult About()
{
    // Here TempData is empty
    var messageModel = (MessageModel)TempData["Message"];

    // Here the messageModel object gets null.
    TempData.Keep("Message");

    ViewBag.Message = "Your application description page." + messageModel.message;

    return View();
}

我可以找到一些已經針對 ASP.NET Core MVC 提出的問題並提出了一些答案。 在這里,我正在尋找普通的 ASP.NET MVC 5(在 .NET Framework 4.6.1 上運行)應用程序。

我對比了 DEV、SIT 之間的 UAT 環境 Azure AppService 配置,似乎是一樣的。

ARR Affinity 選項在 Web 應用程序服務配置設置中也設置為“打開” ,因為我們曾經為 state 完整的 web 站點保持打開的選項。

請求任何人的快速幫助以獲得解決方案,因為它現在是一個障礙。

  • TempDataDictionary用於短期實例。 當下一個請求肯定重定向到下一個視圖(適用於一次性消息)時,它的值在當前和后續請求期間可用。 您分配給TempDataDictionary的任何值都將在后續請求完成后被丟棄,作為“正常讀取”。

因此,您當前的請求由以下序列組成:

  • 請求 => ActionResult (ControllerToView)
  • 設置TempDataDictionary
  • 響應 => 重定向結果
  • Request => ViewResult ==> 如果沒有使用KeepPeek方法來持久化數據, TempDataDictionary的內容可能會被丟棄在這里
  • 響應 => 視圖( TempDataDictionary為空)

使用TempDataDictionary的正確方法是直接傳遞值以在當前請求中查看或使用重定向到另一個 controller 操作方法作為后續請求

Controller

public ActionResult ControllerToView()
{
    ...
    TempData["Message"] = "this is a message!";
    ...
    // returning view counts as providing response
    return View();
}

看法

@if (myCondition)
{
    var test = TempData["Message"]; // showing message
    <p>@test</p>
}

上述示例的請求順序如下:

  • 請求 => ActionResult (ControllerToView)
  • 設置TempDataDictionary
  • 響應 => 查看( TempDataDictionary不為空)

如果您使用RedirectResult然后嘗試在TempData中讀取/顯示值而不指定“下一個操作”,則將其視為“正常讀取”並且不會為下一個請求保留。 您可以使用的“下一個操作”: KeepPeek (在視圖中或 controller 操作):

// Keep
var test = TempData["Message"];
TempData.Keep("Message");

// Peek
var test = TempData.Peek("Message");

注意:如果您希望設置值在多個請求中保持不變,請使用HttpSessionState

// set session state
Session["Message"] = "[any value]";

// read in another request
var testing = Session["Message"];

有關詳細信息,請參閱Azure 的SO 線程和自定義 TempDataProvider。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM