【问题标题】:Model is always null in OnActionExecuting filter asp.net core模型在 OnActionExecuting 过滤器 asp.net 核心中始终为空
【发布时间】:2017-10-26 19:53:57
【问题描述】:

Asp.net core中ActionFilter的OnActionExecuting方法中Model始终为null

(filterContext.Controller as Controller).ViewData.Model

我在 aspnet mvc 3 中找到了一个 worked solution,它在我的 MVC 5 项目中工作。当我使用 Asp.net core 时,这个问题仍然存在,并且没有 DefaultModelBinder。 如何在动作过滤器中获取模型值?

【问题讨论】:

标签: asp.net-mvc asp.net-core


【解决方案1】:

您应该能够在上下文中使用ActionArguments 来访问模型。

public class TestActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        //action has parameter "[FromBody]string value"
        string model = context.ActionArguments["value"] as string;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
    }
}

【讨论】:

  • 当 ModelState.IsValid == false 时,我实现了 ValidateModelStateFilter 并返回一个 ViewResult(此结果中的模型类似于 CustomDefaultModelBinder)。因此,通过参数名称获取模型是一个坏主意。但是感谢您的帮助
猜你喜欢
  • 2019-01-25
  • 2021-10-07
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 2017-06-26
  • 2019-12-28
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多