通过路由访问/login时如何重定向到登录页面? C# MVC

问题描述 投票:0回答:1

我希望能够通过“websiteBaseAddress/login”进入登录页面,如果可能的话,如何使用 c# mvc 中的路由来做到这一点?顺便说一句,我与 Identity 合作,它有自己的区域。

c# asp.net model-view-controller routes
1个回答
0
投票

创建一个AuthorizeAttribute类:

using System.Web.Mvc;

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // Redirect to the login page
            filterContext.Result = new RedirectResult("~/Account/Login");
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

然后将该属性应用到您的控制器或操作:

[CustomAuthorize]
public class YourController : Controller
{
    // Your controller actions
}

如果需要,将该属性应用于特定的操作方法:

public class YourController : Controller
{
    [CustomAuthorize]
    public ActionResult SomeAction()
    {
        // Your action logic
    }
}

在 StartUp.cs 中配置您的路由:

   routes.MapRoute(
        name: "Login",
        url: "Account/Login",
        defaults: new { controller = "Account", action = "Login" }
    );

// Other routes...
© www.soinside.com 2019 - 2024. All rights reserved.