[英]Is there a way to pass an instance of DbContext from the controller to an ActionFilter?
我在ASP.NET MVC 5框架的顶部有一个使用c#编写的应用程序。
我通过继承ActionFilterAttribute
类创建了一个自定义动作过滤器(即ValidateCookieValueAction
)。 我将ValidateCookieValueAction
属性用于多个操作方法。
过滤器的目的是在允许用户执行操作之前,确保用户具有cookie值。 尽管存在安全隐患,但过滤器的效果很好。 但是,cookie值本身需要在让用户进入之前进行验证。
为了验证cookie值,我需要一个DbContext
实例,以便查询数据库并验证cookie值。
我知道我可以直接在ActionFilter中创建DbContext
的新实例。 但是,我想证明这一点。 我希望能够传递已经从控制器中创建的DbContext
实例,以允许我重复使用已经在控制器中建立的连接。
这是我的控制器设置方式
public class BaseController
{
protected IDbContext Context { get; private set; }
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Context = new DbContext();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Context.Dispose();
}
base.Dispose(disposing);
}
}
public class TestController : BaseController
{
[ValidateCookieValueAction]
public ActionResult Index()
{
// the uses is in!
return View();
}
}
这是我的动作过滤器类
public class ValidateCookieValueAction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var cookie = new CookieJar(filterContext.HttpContext);
if (!cookie.Has(ContactListCookieName))
{
var Url = new UrlHelper(filterContext.RequestContext);
var url = Url.Action("Guest", "Test");
filterContext.Result = new RedirectResult(url);
}
}
}
如何将Context
实例传递给ValidateCookieValueAction
?
这与原始问题没有直接关系,但是似乎您是在自己创建身份验证机制 。 如果没有,请告诉我; 我将删除此答案。
ASP.NET已经具有ASP.NET标识 ,它比我们自己创建的更为安全,可靠。 但是,如果要使用现有的自定义表,则可以使用OWIN中间件,该中间件基本上是ASP.NET Identity的子集。
使用OWIN中间件的主要优点是可以使用ASP.NET MVC附带的Authorize属性。 实施比您想象的要容易得多。
示例代码-
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
public void SignIn(User user, IList<string> roleNames)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
foreach (string roleName in roleNames)
{
claims.Add(new Claim(ClaimTypes.Role, roleName));
}
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
[Authorize(Roles = "CanViewHome")]
public class IndexController : Controller
{
[Authorize(Roles = "CanEditHome")]
public ActionResult Edit()
{
return View();
}
}
默认情况下,已有上下文存储在当前上下文中。
在Startup.Configuration(IAppBuilder应用)中
app.CreatePerOwinContext(ApplicationDbContext.Create); // this already stores a DbContext
你可以用
var dbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
或者,您可以将上下文存储在[TempData]或[Session]中。
如果在同一请求中重新获取它,则只需将DbContext扔到Context.Items []中,这些仅在当前请求中持续。
在OnActionExecuting中:
filterContext.Controller.TempData
在控制器中:
this.TempData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.