2016-12-17 135 views
1

我想將通知保存在TempData中並向用戶顯示。我爲此創建了擴展方法並實現了從ActionResult擴展的類。我需要訪問TempData 方法ActionContext在ExecuteResult中訪問TempData Asp.Net MVC Core

擴展方法:

public static IActionResult WithSuccess(this ActionResult result, string message) 
{ 
    return new AlertDecoratorResult(result, "alert-success", message); 
} 

擴展的ActionResult類。從控制器

return RedirectToAction("Index").WithSuccess("Category Created!"); 

public class AlertDecoratorResult : ActionResult 
{ 
     public ActionResult InnerResult { get; set; } 
     public string AlertClass { get; set; } 
     public string Message { get; set; } 
    public AlertDecoratorResult(ActionResult innerResult, string alertClass, string message) 
    { 
     InnerResult = innerResult; 
     AlertClass = alertClass; 
     Message = message; 
    } 

    public override void ExecuteResult(ActionContext context) 
    { 
     ITempDataDictionary tempData = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionary)) as ITempDataDictionary; 

     var alerts = tempData.GetAlert(); 
     alerts.Add(new Alert(AlertClass, Message)); 
     InnerResult.ExecuteResult(context); 
    } 
} 

調用擴展方法我得到 'TempData的' 空,我如何才能獲得 'TempData的' IN '的ExecuteReuslt' 的方法。

enter image description here

回答

0

我找到了得到TempData的方法。它需要從ITempDataDictionaryFactory

var factory = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory; 
var tempData = factory.GetTempData(context.HttpContext); 
2

我是從字面上想今天做同樣的事情(我們已經看到了同樣的Pluralsight課程?;-))和你的問題使我找到了如何訪問TempData的(感謝!)。

調試時,我發現我的ExecuteResult覆蓋從未被調用,這導致我嘗試新的異步版本。這工作!

你需要做的是覆蓋ExecuteResultAsync代替:

public override async Task ExecuteResultAsync(ActionContext context) 
{ 
    ITempDataDictionaryFactory factory = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory; 
    ITempDataDictionary tempData = factory.GetTempData(context.HttpContext); 

    var alerts = tempData.GetAlert(); 
    alerts.Add(new Alert(AlertClass, Message)); 

    await InnerResult.ExecuteResultAsync(context); 
} 

不過,我還沒有完全理解爲什麼異步方法被稱爲控制器不是異步......需要做一些閱讀...

+1

是的,我們看相同的課程。我調用了ExecuteResult,但它沒有在TempData中保留警報。我嘗試了異步方法,但問題仍然存在。警報並沒有持續存在,也沒有顯示出來。你有能力做到這一點嗎? – Ahmar

+0

(對不起,關於延遲,新的一年來臨之間:-)是的,它適用於我,我可以在我的視圖中訪問TempData.GetAlerts,並從那裏獲取數據...不知道可能會有什麼不同: - /我必須啓用會話,其中涉及添加nuget包「Microsoft.AspNetCore.Session」和「Microsoft.Extensions.Caching.Memory」,然後添加「services.AddMemoryCache(); services.AddSession();」在Startup.cs中的ConfigureServices方法中。和「app.UseSession();」在Configure方法中。 –

+0

我在做同樣的事情,但是當在視圖中訪問TempData時,它總是空的? – Cocowalla