如何从ASP.NET CORE ActionFilter中的ActionExecutingContext对象访问ModelState和ValueProvider对象

问题描述 投票:0回答:1

一般在ASP.NET MVC中,在ActionFilterAttribute的OnActionExecuting方法中,我们会得到如下所示的ModelState和ValueProvider:

context.Controller.ViewData.ModelState and context.Controller.ValueProvider

我们如何在 ASP.NET CORE MVC 的 OnActionExecuting 方法中获取 ModelState 和 ValueProvider 对象?

c# asp.net-core asp.net-core-mvc asp.net-core-3.1
1个回答
1
投票

首先,如果你想获取ModelState,你可以使用:

context.ModelState

如果你想获取ActionFilter中的数据,你可以使用

context.ActionArguments["xxx"]
,这里有一个演示:

型号:

public class MySampleModel
    {
        [Required]
        public string Name { get; set; }
    }

行动:

[HttpGet]
        public IActionResult TestActionFilterAttribute()
        {
            return View();
        }
        [HttpPost]
        [MySampleActionFilter]
        public IActionResult TestActionFilterAttribute(MySampleModel mySampleModel) {
            return Ok();
        }

查看:

@model MySampleModel
<form method="post">
    <input asp-for="Name" />
    <input type="submit" value="submit" />
</form>

MySampleActionFilter属性:

public class MySampleActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                
            }
            var s = context.ActionArguments["mySampleModel"] as MySampleModel;
        }


        public override void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
    }

结果:

© www.soinside.com 2019 - 2024. All rights reserved.