【问题标题】:Show views based on authentication status in asp.net mvc在 asp.net mvc 中显示基于身份验证状态的视图
【发布时间】:2017-09-23 02:43:50
【问题描述】:

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

【问题讨论】:

  • RegisterRoutes 不是每次调用都执行一次,而是每次应用启动一次。
  • @RoyDictus 有没有其他方法可以做我想做的事?
  • MSDN上的这篇文章你可能会感兴趣:blogs.msdn.com/b/webdev/archive/2013/10/20/…
  • 如果您从 Visual Studio 2013 中的模板创建一个新的 MVC 应用程序,您几乎可以满足您的需求。并且不要检查HttpContext.Current.User 是否为空。这是不正确的,会给你错误的结果。

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity


【解决方案1】:

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

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

假设你有这样的动作方法:

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

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

[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] 属性位于操作方法上方,如果用户没有登录,他们将被重定向到登录。

【讨论】:

  • 您在技术上是正确的,但我想要的恰恰相反。希望我的启动页面设置为登录,如果用户登录重定向到主页
  • 您可以在全局过滤器中注册 Authorize 属性 - blogs.msdn.com/b/rickandy/archive/2011/05/02/…
  • 身份框架FormsAuthentication 中的@Alex 应在web.config 中禁用。但其他一切都是正确的。
【解决方案2】:

创建您自己的授权属性:

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

【讨论】:

  • 这样会发生额外的浏览器重定向
【解决方案3】:

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

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 将由 Account 或 Department 控制器根据 Request.IsAuthenticated 属性解析。

更新: 这样可以获得完整的路由能力,但仍需要指定正确的控制器:

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

此链接将始终呈现为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 2016-03-07
    • 2019-12-05
    • 2010-10-22
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多