2

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);
        }
    }
}
4

1 回答 1

3

我们可以使用 Redirect To Action,您可以在 Microsoft 的文档 RedirectToAction中阅读

配置 DI:

   public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Add the temp data provider
    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}


[HttpPost]
public IActionResult Edit(User user)
{
    _userRepository.Save(user);
    TempData["User"] = JsonConvert.SerializeObject(user);
    return RedirectToAction("Edit", new { id = user.Id });
}

另一个例子

[HttpPost]
public IActionResult Edit(User user)
{

      _userRepository.Save(user);
      return RedirectToAction(nameof(UserController.Index), "User");
    } 
于 2019-01-13T19:08:24.370 回答