gpt4 book ai didi

c# - 获取 ASP.NET MVC 4 中由名称给定的方法的属性

转载 作者:行者123 更新时间:2023-12-02 05:26:12 24 4
gpt4 key购买 nike

我正在使用 ravendb 作为存储后端。由于它使用 unit of work 模式,我需要打开 session 、执行操作、保存结果并关闭 session 。我想保持我的代码干净,不要在每个操作中显式调用 session 打开和关闭,所以我将这段代码放在 OnActionExecutingOnActionExecuted 方法中,如下所示:

    #region RavenDB's specifics

public IDocumentSession DocumentSession { get; set; }

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}

this.DocumentSession = Storage.Instance.OpenSession();
base.OnActionExecuting(filterContext);
}

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}

if (this.DocumentSession != null && filterContext.Exception == null)
{
this.DocumentSession.SaveChanges();
}

this.DocumentSession.Dispose();
base.OnActionExecuted(filterContext);
}

#endregion

但有些操作需要连接到 ravendb 而实际上不需要。所以我决定创建自定义属性并标记方法需要用它打开 DocumentSession。这是一个例子:

    //
// GET: /Create

[DataAccess]
public ActionResult Create()
{
return View();
}

然后我卡住了。我的计划是在 OnActionExecuted 方法中检索操作的属性,如果存在 [DataAccess],则打开 DocumentSession

OnActionExecuted 中,我可以通过 filterContext.ActionDescriptor.ActionName 语句检索操作名称(方法名称)。但是如何使用反射检索给定类的方法属性?

我发现它可能是 Attribute.GetCustomAttributes 调用,但我得到的最接近 — 我需要有方法的 MemberInfo 对象。但是我如何才能为名称给定的方法获取此 MemberInfo

最佳答案

如果您从 FilterAttribute 继承自定义属性,它将具有 OnActionExecuted 和 OnActionExecuting 方法。并且会在一般的OnActionExecuted和OnActionExecuting之前执行。

例子:

public class DataAccessAttribute: FilterAttribute, IActionFilter
{

public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}
var controller = (YourControllerType)filterContext.Controller;
controller.DocumentSession = Storage.Instance.OpenSession();
}

public void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}
var controller = (YourControllerType)filterContext.Controller;
documentSession = controller.DocumentSession;
if (documentSession != null && filterContext.Exception == null)
{
documentSession.SaveChanges();
}

documentSession.Dispose();
}

关于c# - 获取 ASP.NET MVC 4 中由名称给定的方法的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064646/

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