C# 获取ASP.NET MVC 4中按名称给定的方法的属性
我正在使用C# 获取ASP.NET MVC 4中按名称给定的方法的属性,c#,asp.net-mvc,reflection,ravendb,C#,Asp.net Mvc,Reflection,Ravendb,我正在使用ravendb作为存储后端。由于它使用工作单元模式,我需要打开会话、执行操作、保存结果并关闭会话。我想保持代码干净,不在每个操作中显式调用会话打开和关闭,因此我将此代码放入OnActionExecuting和onactionexecutive方法中,如下所示: #区域RavenDB的详细信息 公共IDocumentSession DocumentSession{get;set;} 受保护的覆盖无效OnActionExecuting(ActionExecutingContext filt
ravendb
作为存储后端。由于它使用工作单元
模式,我需要打开会话、执行操作、保存结果并关闭会话。我想保持代码干净,不在每个操作中显式调用会话打开和关闭,因此我将此代码放入OnActionExecuting
和onactionexecutive
方法中,如下所示:
#区域RavenDB的详细信息
公共IDocumentSession DocumentSession{get;set;}
受保护的覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
if(filterContext.IsChildAction)
{
返回;
}
this.DocumentSession=Storage.Instance.OpenSession();
base.OnActionExecuting(filterContext);
}
受保护的覆盖无效OnActionExecuted(ActionExecutedContext筛选器上下文)
{
if(filterContext.IsChildAction)
{
返回;
}
if(this.DocumentSession!=null&&filterContext.Exception==null)
{
this.DocumentSession.SaveChanges();
}
this.DocumentSession.Dispose();
base.OnActionExecuted(filterContext);
}
#端区
但是有些操作需要连接到ravendb,而come不需要。所以我决定创建自定义属性,标记方法需要使用它打开DocumentSession。以下是一个例子:
//
//获取:/Create
[数据存取]
公共操作结果创建()
{
返回视图();
}
我卡住了。我的计划是在OnActionExecuted
方法中检索操作的属性,如果存在[DataAccess]
,请打开DocumentSession
在OnActionExecuted
中,我可以通过filterContext.ActionDescriptor.ActionName
语句检索操作名(方法名)。但如何使用反射检索给定类的方法属性呢
我发现它可能是
Attribute.GetCustomAttributes
调用,但我得到的最接近-我需要方法的MemberInfo
对象。但是我如何才能为名称给定的方法获取此MemberInfo
?为什么不让您的DataAccess
属性继承,以便您可以将ActionExecuting/Executed方法放在属性上而不是控制器上
通过使用操作筛选器在基本控制器上设置会话。它是使用NHibernate完成的,但与您需要做的非常类似,它是由Ayende编写的,我相信他是RavenDB的作者之一。如果您从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();
}
嗯<代码>文档会话应属于控制器实例。否则,我将能够保存和检索数据。或者我需要想出执行这个的方法。在filterContext中有ControllerBase Controller的实例。您可以将其强制转换为控制器的类型,并获取其任何属性。我更新了我的答案。谢谢,听起来像是我一直在寻找的答案!一件小事:在这种情况下,对
base
的调用是非法的。很好!谢谢你,基里尔!