为了
ViewData
,无法通过解决
context.HttpContext.RequestServices.GetService
.
/// <summary>
/// Gets or sets <see cref="ViewDataDictionary"/> used by <see cref="ViewResult"/> and <see cref="ViewBag"/>.
/// </summary>
/// <remarks>
/// By default, this property is intiailized when <see cref="Controllers.IControllerActivator"/> activates
/// controllers.
/// <para>
/// This property can be accessed after the controller has been activated, for example, in a controller action
/// or by overriding <see cref="OnActionExecuting(ActionExecutingContext)"/>.
/// </para>
/// <para>
/// This property can be also accessed from within a unit test where it is initialized with
/// <see cref="EmptyModelMetadataProvider"/>.
/// </para>
/// </remarks>
[ViewDataDictionary]
public ViewDataDictionary ViewData
如上所述,您只能访问
可视数据
在里面
Controller
和
OnActionExecuting(ActionExecutingContext)
. 您无法通过解析的服务访问它。
你可以试着进入
可视数据
通过反射
IActionResult
.
尝试
public static class ActionResultExtension
{
public static IActionResult WithTitle(this IActionResult action, string modalTitle)
{
return new ModalTitleDecorator(action, modalTitle);
}
}
public class ModalTitleDecorator : PartialViewResult
{
private readonly IActionResult _actionResult;
private readonly string _modalTitle;
public ModalTitleDecorator(IActionResult action, string modalTitle)
{
_actionResult = action;
_modalTitle = modalTitle;
}
public override async Task ExecuteResultAsync(ActionContext context)
{
ViewDataDictionary viewData = _actionResult
.GetType()
.GetProperty("ViewData")
.GetValue(_actionResult) as ViewDataDictionary;
if (viewData != null)
{
viewData["Title"] = _modalTitle;
}
await _actionResult.ExecuteResultAsync(context);
}
}