如果用户已登录,我想显示我的部门 View ,如果未登录,我想显示登录页面。我在我的 RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
if (HttpContext.Current.User==null)
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
else
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Department", action = "Index", id = UrlParameter.Optional }
);
}
}
但是这个总是在启动时加载登录页面。任何人都可以指出我在这里做错了什么吗? 注意:我正在使用 Asp.net Identity对于这个应用
最佳答案
您的 HttpContext.Current.User==null
逻辑将进入 Controller ,而不是您的路由注册
注意 - 正确的调用是 Request.IsAuthenticated
假设您有这样的操作方法:
public ViewResult Index()
{
if(Request.IsAuthenticated)
return new RedirectResult("toLoginPage")
else
return new View("loggedInView");
}
但是,我相信 [Authorize]
属性可能是您在用例中想要的:(注意 - 重新阅读问题后,这个可能不准确,因为您想根据登录状态返回不同的 View )
[Authorize]
public ViewResult ShowPerson(int id)
{
return new View("loggedInView");
}
在你的 web.config 中,类似
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" />
</authentication>
</system.web>
在此特定实例中,通过操作方法上方的 [Authorize]
属性,如果用户未登录,他们将被重定向到登录。
关于c# - 在 asp.net mvc 中显示基于身份验证状态的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538519/