【问题标题】:MVC C# Redirecting to another controllerMVC C# 重定向到另一个控制器
【发布时间】:2016-03-04 12:12:49
【问题描述】:

我在从一个控制器重定向到另一个控制器时遇到问题,我的 ASP.NE MVC 应用程序在登录页面上启动,然后在用户成功登录时移动到 otp 页面(登录和 OTP 操作在同一个控制器中)。

当 OTP 成功提交后,应用程序必须继续到菜单页面,但它会重定向回登录页面。

AuthenticateController: 登录操作

// POST: /Authenticate/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(ViewModel_Login model)
{
        // do login validation
        if (loggedin)
        {
            return View("OTPAuthentication");
        }
        else
        {
            return View(model);
        }
}

AuthenticateController:OTPAuthentication 操作

// POST: /Authenticate/OTPAuthentication
[HttpPost]
[AuthorizeUser]
[ValidateAntiForgeryToken]
public ActionResult OTPAuthentication(ViewModel_OTP model)
{
        if (ModelState.IsValid)
        {
            // do OTP validation
            return this.RedirectToAction("MainMenu", "Options");
        }
        else
        {
            ModelState.AddModelError("", "The one time pin provided is incorrect.");
        }

        return View(model);
}

OptionsController: 主菜单操作

// GET: /Options/MainMenu
[AuthorizeUser]
public ActionResult MainMenu()
{
        return View();
}

RouteConfig:

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Authenticate", action = "Login", id = UrlParameter.Optional });

routes.MapRoute(
name: "Menu",
url: "Menu",
defaults: new { controller = "Options", action = "MainMenu" });

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

routes.MapRoute(
name: "OTP",
url: "OTP",
defaults: new { controller = "Authenticate", action = "OTPAuthentication" });

【问题讨论】:

  • MainMenu 操作的默认视图是什么?指定了吗?
  • MainMenu 仅包含 3 个链接到第三个控制器的按钮

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


【解决方案1】:

如果您使用 forms authentication,那么在将用户重定向到 MainMenu 控制器之前,您必须执行类似操作。

if (ModelState.IsValid)
   {
       string userName = "user123";
       FormsAuthentication.SetAuthCookie(userName , True)
       // do OTP validation
       return this.RedirectToAction("MainMenu", "Options");
    }
    else
    ....

【讨论】:

    【解决方案2】:

    感谢您的帮助。

    我发现了我的问题。因为我使用自己的登录服务,所以我不得不重写 AuthorizeAttribute 并且在一些自定义授权属性教程中,他们说我应该包括以下内容:

    var isAuthorized = base.AuthorizeCore(httpContext);
    if (!isAuthorized)
    {
        return false;
    }
    // do try/catch that validate the session and the session security
    

    所以我所要做的就是删除这段代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      相关资源
      最近更新 更多