在ASP.NET MVC中使用Spring.Net 参考:ASP.NET MVC Spring.NET 整合
在ASP.NET MVC中写了一个FilterController,override OnActionExecuting()方法,于是可以借助session实现单点登录 但是使用Spring.Net实现依赖注入却一直为null。
public class FilterController : Controller
{
//在这里不能使用Spring.Net的依赖注入 为什么?
IUserService userService = new BLL.UserService();
IBLL.IAuthorityService authService = new BLL.AuthorityService();
//过滤器不能使用Spring.Net的依赖注入
//比如访问SettingController,访问Action之前会进入FilterController 但是这是MVC框架内部执行的
//其实还是在访问Setting/Index,所以Spring.Net不会生成Filter控制器下的属性
//public IUserService userService { get; set; }
//public IBLL.IAuthorityService authService { get; set; }
//在调用操作方法前执行
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
//没有session的情况
if (!hasSession())
{
//没有Session检查cookie
if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null)
{
string cookieNameValue = Request.Cookies["cp1"].Value;
string cookiePwdValue = Request.Cookies["cp2"].Value;
var model = userService.LoadEntities(c => c.LoginName == cookieNameValue).FirstOrDefault();
if (model != null)
{
if (cookiePwdValue == ControllersCommon.ControllersCommon.GetPwdMd5(model.LoginPwd))//注意,注册时将密码加密以后保存到数据库。
{
//Session为空,而cookie不为空 需要给Session赋值
SaveToSession(model);
return;
}
}
else
{
//删除Cookie.
DeleteCookies();
}
}
else//cookie不存在
{
//什么也不用做
}
//用户没有登录 session没有 也没有缓存 记录跳转页 进行过滤操作
ControllersCommon.ControllersCommon.GoPageUrl();
}
//有session 在session规定的过期时间之内,任意转跳
else
{
//不进行过滤
//进行权限检查
if (!CheckAuthority())
{
filterContext.HttpContext.Response.Redirect("/Error/NoAuthority/Index");
}
}
}
}
原因就是
//过滤器不能使用Spring.Net的依赖注入
//比如访问SettingController,访问Action之前会进入FilterController 但是这是MVC框架内部执行的
//其实还是在访问Setting/Index,所以Spring.Net不会生成Filter控制器下的属性