gpt4 book ai didi

c# - 在 Web API 调用的 OnActionExecuting 期间 - 如何从路由字符串映射到 Controller /操作类以读取操作属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:56 24 4
gpt4 key购买 nike

如何将传入路由字符串(例如 Products/GetProduct)映射到将被调用的 Controller /方法(ProductsController、GetProduct 方法)?

我的目标是检查 ProductsContoller 的实例以找到放置在 GetProduct 方法上的自定义属性。

一旦我知道我正在处理哪个类/方法,我就知道如何检查类。

我考虑过只拆分字符串,所以您最终会得到“Products”和“GetProducts”,然后我可以查找 ProductsController,并在其中查找名为 GetProducts 的方法。

这可能有效,但似乎应该有更好的解决方案。有什么想法吗?

最佳答案

您可以使用以下方法获取操作的实际 Controller 实例和属性:

public class Somefilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var controller = actionContext.ControllerContext.Controller;
var someFilterattributes = actionContext.ActionDescriptor.GetCustomAttributes<Somefilter>()
var otherAttributes = actionContext.ActionDescriptor.GetCustomAttributes<Other>()
}
}

Other 是操作的其他过滤器。

关于c# - 在 Web API 调用的 OnActionExecuting 期间 - 如何从路由字符串映射到 Controller /操作类以读取操作属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23713130/

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