我想实现一个使用Ajax.Beginform的登录表单。我已经实现了代码,但是我有一个问题,在ajax发布并设置Authentication cookie之后,控制器返回视图,但是IsAuthenticate方法在_Layout视图中返回false:
这是我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using USCSAR.Manager;
namespace USCSAR.Controllers
{
public class HomeController : Controller
{
Manager.ManagerJMBG manager = new ManagerJMBG();
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
return View(new ViewModel.ViewJMBG());
}
[HttpPost]
[AllowAnonymous]
public ActionResult Login(string _jmbg)
{
string errorMassage = "Neispravan, logicki netacan unet JMBG !";
if (ModelState.IsValid && !string.IsNullOrEmpty(_jmbg))
{
bool valid = Common.JMBG.IsValid(_jmbg);
if (!valid)
{
return View("LoggerManagerPartial");
}
try
{
bool isUserExists = manager.IsUserExist(_jmbg);
if (!isUserExists)
{
manager.CreateNewUser(_jmbg);
FormsAuthentication.SetAuthCookie(_jmbg, true);
return View("LoggerManagerPartial");
}
else
{
FormsAuthentication.SetAuthCookie(_jmbg, true);
return View("LoggerManagerPartial");
}
}
catch (Exception)
{
return View("Error");
}
}
else
{
ModelState.AddModelError("", "JMBG korisnika je neispravan!");
return Json(errorMassage);
}
}
[HttpGet]
[AllowAnonymous]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
}
_Layout:
@model USCSAR.ViewModel.ViewJMBG
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div id="LoginContent" style="background-color: gray; color: black">
@Html.Partial("LoggerManagerPartial", Model)
</div>
</header>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
<script src="~/CustomScripts/FailureLogin.js"></script>
</body>
</html>
LoggerManagerPartial:
@if (Request.IsAuthenticated)
{
<strong>@Html.Encode(User.Identity.Name)</strong>
<br />
@Html.ActionLink("Odjavi se", "Logout", "Home");
}
else
{
using (Ajax.BeginForm("Login", "Home", new AjaxOptions
{
HttpMethod = "POST",
OnFailure = "FailureLogin(data)",
OnSuccess = "SuccessLogin()",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "LoginContent"
}))
{
<input type="text" id="_jmbg" name="_jmbg" onkeypress="IsNumberKey(event)" />
<input type="submit" value="bla" />
}
<br/>
<label id="errorMassage">Error Label</label>
}
日Thnx
答案 0 :(得分:1)
我认为问题可能与Request.IsAuthenticated
有关 - 请参阅此问题How does Request.IsAuthenticated work?。
根据这个问题的答案:asp.net mvc authentication cookie issue你需要使用
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
获取cookie然后解密并获取用户名
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData
希望有所帮助。