根据 asp.net mvc 中的身份验证状态显示视图

Show views based on authentication status in asp.net mvc

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

    }

但是这个总是在 startup.Can 加载登录页面 有人指出我在这里做错了什么吗? 注意:我正在为这个应用程序使用 Asp.net Identity

您的 HttpContext.Current.User==null 逻辑将进入控制器,而不是您的路由注册

注意-正确的调用是Request.IsAuthenticated

假设您有这样的操作方法:

public ViewResult Index()
{
  if(Request.IsAuthenticated)
    return new RedirectResult("toLoginPage")
  else
    return new View("loggedInView");
}

但是,我相信 [Authorize] 属性可能是您在用例中想要的:(注意 - 重新阅读问题,这可能不准确,因为您想 return 根据登录状态获得不同的视图)

[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] 属性,如果用户未登录,他们将被重定向到登录。

创建您自己的授权属性:

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" }));
        }
    }
}

然后将 [CustomAuthorize] 添加到您的控制器并更改它指向的路由。

这取自here

您可以通过路由约束来实现:

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 }
        );
    }
}

在此示例中,~/AuthArea url 将由帐户或部门控制器根据 Request.IsAuthenticated 属性.

解析

更新: 这样就得到了完整的路由能力,但是还是需要指定正确的controller:

@Html.ActionLink("Context dependent link", "Index", @Request.IsAuthenticated ? "Account" : "Department")

此 link 将始终呈现为:

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