C# 在asp.net mvc中显示基于身份验证状态的视图

C# 在asp.net mvc中显示基于身份验证状态的视图,c#,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-identity,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 5,Asp.net Identity,如果用户已登录,我想显示我的部门视图,如果未登录,我想显示登录页面。我在我的RouteConfig public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); if (HttpContext.Current.User==null) { routes.M

如果用户已登录,我想显示我的部门视图,如果未登录,我想显示登录页面。我在我的
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 }
               );
        }

    }
但这个总是在启动时加载登录页面。有人能指出我在这里做错了什么吗?
注意:我正在为此应用程序使用您的
HttpContext.Current.User==null
逻辑,而不是您的路由注册

注意-正确的呼叫是
Request.IsAuthenticated

假设您有这样一种操作方法:

public ViewResult Index()
{
  if(Request.IsAuthenticated)
    return new RedirectResult("toLoginPage")
  else
    return new View("loggedInView");
}
但是,我相信
[Authorize]
属性可能是您在用例中想要的:(注意-重新阅读问题后,这可能不准确,因为您希望根据登录状态返回不同的视图)

在web.config中,类似

<system.web>
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" />
</authentication>
</system.web>


在此特定实例中,使用action方法上方的
[Authorize]
属性,如果用户未登录,则会重定向到登录。

创建您自己的授权属性:

public class CustomAuthorize: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new{ controller = "Error", action = "AccessDenied" }));
        }
    }
}
然后将[CustomAuthorization]添加到控制器并更改其指向的路线


这是从

中提取的。您可以通过路线约束实现这一点:

public class DelegateConstraint : IRouteConstraint
{
    private readonly Func<HttpContextBase, bool> _isMatch;

    public DelegateConstraint(Func<HttpContextBase, bool> isMatch)
    {
        _isMatch = isMatch;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return _isMatch(httpContext);
    }
}

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "CustomAuth1",
            url: "AuthArea/{action}/{id}",
            defaults: new { controller = "Department", action = "Index", id = UrlParameter.Optional },
            constraints: new { auth = new DelegateConstraint(httpContext => !httpContext.Request.IsAuthenticated) }
            );

        routes.MapRoute(
            name: "CustomAuth2",
            url: "AuthArea/{action}/{id}",
            defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional },
            constraints: new { auth = new DelegateConstraint(httpContext => httpContext.Request.IsAuthenticated) }
            );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
此链接将始终呈现为:

<a href="/AuthArea">Context dependent link</a>


RegisterRoutes不是每次调用执行一次,而是每次应用程序启动执行一次。@RoyDictus是否有其他方法可以执行我想要的操作?这篇关于MSDN的文章可能会引起您的兴趣:如果您在Visual Studio 2013中从模板创建一个新的MVC应用程序,您将非常需要它。不要检查
HttpContext.Current.User
是否为空。这是不正确的,会给你错误的结果。你在技术上是正确的,但我想要的恰恰相反。要将我的启动页面设置为登录,并且如果用户登录重定向到主页,则可以在全局筛选器中注册Authorize属性-@Alex in Identity framework
forms应在
web.config
中禁用身份验证。但其他一切都是正确的。这样会发生额外的浏览器重定向
@Html.ActionLink("Context dependent link", "Index", @Request.IsAuthenticated ? "Account" : "Department")
<a href="/AuthArea">Context dependent link</a>