使用Razor的FormsAuthentication无效

我试图让FormsAuthentication与我的Razor应用程序(MVC 3)一起使用。 我有一个LoginController调用我的LoginPage(在Views / Shared中); 我的web.config将LoginUrl设置为“/ Login /”。 当应用程序尝试调出主页面时,[Authorize]行会正确显示LoginPage,但问题就出现了。

这是我的LoginController.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ABMCEditAndReports.Controllers { public class LoginController : Controller { // // GET: /Login/ public ActionResult Index() { return View("LoginPage"); } } } 

这是我的LoginPage.cshtml:

 @{ ViewBag.Title = "Login Page"; ViewBag.Header = "Login Page"; }  $.ajaxSetup({ cache: false }); function onClickLogin() { if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false); } else { lblErrorMessage.Text = "This works better if you use YOUR user name and password"; } }  

Login Required

User Name:
Password:

第一个问题是,当我启动应用程序时,VS停止在$ .ajaxSetup行,“Microsoft JScript运行时错误:’$’未定义”。

当我对此进行评论时,页面会显示,但是当我按下“登录”按钮时,它会在Membership.ValidateUser行停止,并显示“Microsoft JScript运行时错误:’成员身份’未定义”。

请注意,$ .ajaxSetup行在我的所有其他视图页面上都能正常工作。

我尝试将“@using System.Web.Security”添加到LoginPage.cshtml,并将命名空间System.Web.Security添加到web.config(主要的一个和/ Views中的一个); 没有什么能解决的。

我是以正确的方式来做这件事的吗? 我应该在.cs文件中调用ValidateUser吗? 如果是这样,我该如何调用RedirectFromLoginPage? (为什么不接受$ .ajaxSetup?)

FormsAuthentication与ASP.NET MVC一起使用,但尝试在服务器上进行身份validation。 这是一个例子:

控制器:

 namespace ABMCEditAndReports.Controllers { public class LoginController : Controller { // // GET: /Login/ public ActionResult Index(string returnUrl = null) { this.ViewBag.ReturnUrl = returnUrl; return View("LoginPage"); } public ActionResult Index(LogInViewModel model, string returnUrl) { if (this.ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, false); return this.Redirect(returnUrl); } this.ModelState.AddModelError("", "The user name or password provided is incorrect."); return this.View(model); } } } 

模型:

 namespace ABMCEditAndReports.Models { public class LogInViewModel { [Display(Name = "User Name")] public string UserName { get; set; } [Display(Name = "Password")] [DataType(DataType.Password)] public string Password { get; set; } } } 

视图:

 @model ABMCEditAndReports.Models.LogInViewModel @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.ValidationSummary() 

Please sign in

@Html.DisplayNameFor(model => model.UserName) @Html.EditorFor(model => model.UserName)
@Html.DisplayNameFor(model => model.Password) @Html.EditorFor(model => model.Password)
}