gpt4 book ai didi

asp.net-mvc-2 - 如何将动态变量传递给 ASP.NET MVC 中的 Action 过滤器

转载 作者:行者123 更新时间:2023-12-04 06:04:21 24 4
gpt4 key购买 nike

我想使用一个变量将动态值传递给我的操作过滤器。我以为会是这样的:

[MessageActionFilter(message = "User is updating item: " & id)]
public ActionResult doSomething(int id)
{
// do something
}

然而,似乎参数必须是一个常数值。因此,我的问题是如何将变量添加到我的操作过滤器中?

最佳答案

您可以使用 ActionExecutingContext.ActionParameters 在 OnActionExecuting 中获取参数值。属性(property)。

这只是一个伪代码,但例如您可以检索名为 id 的参数

public class MessageActionFilter: ActionFilterAttribute 
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;

var parameterValue = filterContext.ActionParameters.SingleOrDefault(p => p.Key == "id");

// check if not null before writing a message

response.Write(this.Message + parameterValue); // prints "User is updating item: <idvalue>"
}

public string Message {get; set;}
}

告诉我是否有帮助。

关于asp.net-mvc-2 - 如何将动态变量传递给 ASP.NET MVC 中的 Action 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com