首页 > 解决方案 > Asp.net Mvc 5,两个帐户控制器和区域但重定向到错误的登录页面

问题描述

我的 mvc 5 项目中有和 Area 。在区域中,我已经从我的项目的根目录和 AccountController 复制了控制器。

我有一个 NewsController 的创建表单和控制器,它在类的开头具有 [Authorize] 属性。

但是,当未登录并想要创建新闻时,表单会返回到我的项目的 root 登录,而不是区域部分。

这些是我的控制器和视图部分:

项目结构:

创建.cshtml:

@using (Html.BeginForm("Create", "News", FormMethod.Post,
                                    new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
 ....

新闻控制器.cs:

 namespace Project.Areas.Admin.Controllers
    {
        [Authorize]
        public class NewsController : Controller
        {
             ...
        }

          public ActionResult Create()
                {            
                        return View();            
                }
     }

并且 AccountController.cs 在根控制器文件夹中是相同的。

请记住:我已添加

新 {area="Admin"}

形成但是,重定向再次转到root的登录登录页面,而不是Areas/Admin/login

@using (Html.BeginForm("Create", "News", FormMethod.Post,new {area="Admin"},
                                    new { enctype = "multipart/form-data"}))

标签: c#asp.net-mvcredirectauthorization

解决方案


您将被重定向到默认登录路由。如果要更改默认登录路由,请在 App_Start\Startup.Auth.cs 文件中进行配置。

public void ConfigureAuth(IAppBuilder app)
{
    // Configure the db context, user manager and signin manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    // Enable the application to use a cookie to store information for the signed in user
    // and to use a cookie to temporarily store information about a user logging in with a third party login provider
    // Configure the sign in cookie
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login")

将LoginPath值更改为所需的值。

要更改特定区域的登录页面: 您需要创建自定义授权属性,例如:

public class AdminAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // If you are authorized
        if (this.AuthorizeCore(filterContext.HttpContext))
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            // else redirect to your Area  specific login page
            filterContext.Result = new RedirectResult("~/Area/Admin/Account/Login");
        }
    }
}

并将其应用于您的区域控制器,如下所示:

[AdminAuthorize]
public class NewsController : Controller
{
    ...
}

推荐阅读