【发布时间】:2016-09-21 22:51:49
【问题描述】:
在 ASP.NET MVC Core 项目中如何使用this custom action filter class 的替代方案。当我将以下内容复制到项目的控制器文件夹中时,它无法识别以下对象TempData[Key], ViewData,因为它使用的 System.Web.Mvc 命名空间未在 ASp.NET MVC Core 中使用。我想在我的 ASP.NET MVC Core 项目as described here 中实现 POST-REDIRECT-GET,但作者似乎没有使用 MVC Core:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace myASPCoreProject.Controllers
{
public abstract class ModelStateTransfer : ActionFilterAttribute
{
protected static readonly string Key = typeof(ModelStateTransfer).FullName;
}
public class ExportModelStateAttribute : ModelStateTransfer
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//Only export when ModelState is not valid
if (!filterContext.ModelState.IsValid)
{
//Export if we are redirecting
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
filterContext.Controller.TempData[Key] = filterContext.ModelState;
}
}
base.OnActionExecuted(filterContext);
}
}
public class ImportModelStateAttribute : ModelStateTransfer
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;
if (modelState != null)
{
//Only Import if we are viewing
if (filterContext.Result is ViewResult)
{
filterContext.Controller.ViewData.ModelState.Merge(modelState);
}
else
{
//Otherwise remove it.
filterContext.Controller.TempData.Remove(Key);
}
}
base.OnActionExecuted(filterContext);
}
}
}
【问题讨论】:
-
这个answer 解释了如何从 DI 服务中获取它。
标签: c# visual-studio-2015 asp.net-core custom-action-filter