如何在控制器中执行方法之前预先填充模型中的某些属性

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

我有多个输入模型,其中大多数包含“OwnerId”和“CreatedBy”属性。我正在寻找一种机制来自动使用默认值填充这些属性。我尝试使用中间件,但在找到上述属性来填充它们时遇到了困难。

[HttpPost]
public async Task<bool> ExportPackingListProductBulkInsert(PackingListProductFromSalePermitInput input)
{
    // input.OwnerId = 10;
    // input.CreatedBy = get current date
    // Inserting process
    return await true;
} 

我有大量的

Actions
,在执行操作之前需要填充它们的输入。是否有一种机制可以自动填充这些输入?

c# .net-core controller middleware
1个回答
0
投票

您可以继承

ActionFilterAttribute
并标记您的API方法。然后,重写此属性上的
OnActionExecuting
方法。

OnActionExecuting
在进入标记的 API 方法之前调用。

您可以通过

ActionExecutingContext.ActionArguments
访问方法参数,这是一个
Dictionary<string, object>
。它的键是参数名称,这里是“input”。您需要将值转换为正确的类型,即
PackingListProductFromSalePermitInput
或其基类之一。

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