2016-12-17 136 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