在ASP.NET MVC Core项目中,如何使用此自定义操作过滤器类的替代方案。当我在项目的控制器文件夹中复制以下内容时,它无法识别以下对象TempData[Key], ViewData
,因为它使用的是 ASp.NET MVC Core 中未使用的 System.Web.Mvc 命名空间。我想在我的 ASP.NET MVC Core 项目中实现 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);
}
}
}