如何通过Authenticated设置默认路由?

时间:2018-02-05 04:01:54

标签: c# asp.net-core-mvc

我希望两个控制器位于相同的路径上,但是一个控制器在没有人登录时处理,另一个控制器在有人通过身份验证时处理。

有没有办法设置它?

1 个答案:

答案 0 :(得分:1)

只是一个例子:

app.UseMvc(routes =>
{
    routes.MapRoute(
        "Logged",
        "SomeUrl",
        new {controller = "Default", action = "Index"},
        new {controller = new MustBeLoggedIn()}
    );

    routes.MapRoute(
        "NotLogged",
        "SomeUrl",
        new { controller = "Auth", action = "Index" }
    );

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}");
});

public class MustBeLoggedIn : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values,
        RouteDirection routeDirection)
    {
        return httpContext.User?.Identity?.IsAuthenticated ?? false;
    }
}

如何设置用户身份验证状态取决于您的选择。