我的MVC5项目结构如下:
Project
- App_Data
- App_Start
- RouteConfig.cs
- Controllers
- AccountController.cs
- HomeController.cs
- Views
- Account
- Index.cshtml
- Home
- Index.cshtml
- web.config
- Global.asax
- Web.config
在视图 - >帐户 - > Index.cshtml是登录页面,其视图现在是:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<p>
from Account
</p>
<input type="submit" value="Post" />
}
</div>
</body>
</html>
AccountController代码是:
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult Login()
{
if (true) //assuming validation is true
{
FormsAuthentication.RedirectFromLoginPage("test", false);
}
return null;
}
}
当用户请求此页面时,将调用Index()方法,当用户单击“提交”按钮时,将触发Login()方法。奇怪的是,当我点击表格POST下的按钮提交按钮时,它在Index()方法中而不是Login()中控制器中的断点。
在检查按钮时,表单标签具有:
<form action="/Account/Login" method="post">
所以我复制了URL并粘贴在浏览器(http://localhost:55136/Account/Login)中,调用了Index()方法而不是Login()。但是,如果我从web.config和FormsAuthentication.RedirectFromLoginPage(“test”,false);中删除了formsauthentication的代码,它可以正常工作。
formsauthentication的Web.config文件是:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Index" defaultUrl="~/Home/Index" >
<credentials passwordFormat="Clear"></credentials>
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
我在RouteConfig.cs文件中的路由是:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我现在不了解MVC的行为。这从未发生过。为什么MVC会这样?如何在提交点击时重定向到Login()?
您的Web.config应该具有如下所示的标记:
<system.web>...</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>