Asp.net Mvc 5,两个帐户控制器和Area,但重定向到错误的登录页面



我的mvc 5项目中有和Area。在这个领域,我已经从我项目的根目录和AccountController中复制了Controllers。

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

但当没有登录并想创建一个新闻时,表单会发布回我项目的root登录,而不是Area部分。

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

项目结构:

  • 区域
    • 管理员
      • 控制器
      • 关于Controller.cs
      • NewsControlle.cs
      • 视图
      • 创建.cshtml

Create.cshtml:

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

NewsController.cs:

namespace Project.Areas.Admin.Controllers
{
[Authorize]
public class NewsController : Controller
{
...
}
public ActionResult Create()
{            
return View();            
}
}

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

记住:我添加了

新{area="Admin"}

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

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

您将被重定向到默认登录路由。如果要更改默认登录路由,请在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")

登录路径值更改为所需值。

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

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
{
...
}

最新更新