OWIN Auth HTTPContext NULL on BaseController
本文关键字:on BaseController NULL HTTPContext Auth OWIN | 更新日期: 2023-09-27 18:18:28
尝试创建一个基本控制器,该控制器在整个站点上继承,因为它根据用户角色动态加载导航栏。
问题是,它似乎总是加载并试图获得用户角色,即使自己还没有加载,用户还没有登录。
下面是名为LayoutController的BaseController
[Authorize]
public class LayoutController : Controller
{
public List<NavigationMenuModel> MainLayoutViewModel { get; set; }
public LayoutController()
{
this.MainLayoutViewModel = new List<NavigationMenuModel>();
using (var context = new OperationalDataContext())
{
//The BELOW LINE IS ISSUE
var username = HttpContext.GetOwinContext().Authentication.User.Identity.Name;
var pages = context.GET_PAGES_BY_USERNAME(username);
var pagesTop = pages.Where(x => x.Parent == null);
foreach (var page in pagesTop)
{
var tmpNM = new NavigationMenuModel();
tmpNM.DisplayName = page.Name;
tmpNM.RelativeUrl = page.RelativeUrl;
var children = pages.Where(x => x.Parent != null && x.Parent.Equals(page.Name) && x.Site.Equals("PRODUCT"));
List<NavigationMenuModel> tmpChildren = new List<NavigationMenuModel>();
foreach (var child in children)
{
var tmpC = new NavigationMenuModel();
tmpC.DisplayName = child.Name;
tmpC.RelativeUrl = child.RelativeUrl;
var children1 = pages.Where(x => x.Parent != null && x.Parent.Equals(child.Name) && x.Site.Equals("PRODUCT"));
List<NavigationMenuModel> tmpChildren1 = new List<NavigationMenuModel>();
foreach (var child1 in children)
{
var tmpC1 = new NavigationMenuModel();
tmpC1.DisplayName = child1.Name;
tmpC1.RelativeUrl = child1.RelativeUrl;
tmpChildren1.Add(tmpC1);
}
tmpC.Children = tmpChildren1;
}
tmpNM.Children = tmpChildren;
this.MainLayoutViewModel.Add(tmpNM);
}
}
this.ViewBag["MainLayoutViewModel"] = this.MainLayoutViewModel;
}
}
然后是dashboardController(主页)
public class DashboardController : LayoutController
{
// GET: Dashboard
public ActionResult Index()
{
return View("Index");
}
}
我们有一个简单的基于cookie的登录是允许匿名的
public class AccountController : Controller
{
IAuthenticationManager AuthenticationManager
{
get { return HttpContext.GetOwinContext().Authentication; }
}
[HttpGet]
[AllowAnonymous]
[Route("login")]
public ActionResult Login()
{
return View("Login");
}
}
}
在startup.css
中public void ConfigureAuthentication(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
});
}
问题似乎是,它没有重定向到登录之前,试图去布局。
AccountController没有引用LayoutController
问题是,你正在做你在控制器的构造函数中做的事情。
Authorize
属性检查用户是否登录,如果没有,则将他/她重定向到登录页面。构造函数代码在控制器创建时执行——在调用任何方法之前。
覆盖OnActionExecuting
在你的LayoutController
和移动构造函数代码那里。我不太确定Authorize
属性是否在 OnActionExecuting
执行之前拦截对控制器方法的调用,但我会尝试一下。
顺便说一下:AllowAnonymous
用于单个方法反转控制器的Authorize
属性。因此,如果您的AccountController
没有设置此属性,则在AllowAnonymous
中没有任何用处。但是这有点跑题了。
希望能有所帮助。