【发布时间】:2012-02-24 17:07:59
【问题描述】:
我有一个正在运行的带有表单身份验证的 MVC 3 (Razor) 应用程序。我可以在部分视图中轻松调用@User.Identety.Name,这将返回登录用户的名称。但是如果我在 Controller 中调用 User.Identety.Name 它会返回 null ...
如果我尝试检查 (User.Identity.IsAuthenticated) 它总是返回 null...
我现在很困惑……
在登录时,我调用登录方法,该方法调用我设置身份验证 cookie 的 SignIn 方法,理论上它必须包含我需要获取的所有数据。
我做错了什么?
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, true);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Brugernavn eller kodeordet er forkert!");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, true);
}
//Upload method is in an Employee Controller.
public string Upload(HttpPostedFileBase fileData)
{
if (User.Identity.IsAuthenticated)
{
var fileName =
this.Server.MapPath("~/uploads/" + HttpContext.User.Identity.Name + "/" +
System.IO.Path.GetFileName(fileData.FileName));
fileData.SaveAs(fileName);
}
return "ok";
}
更新
好的,看来我找到了问题!
如果我在 ActionResult 方法中调用 User.Identety.Name,它会毫无问题地返回用户名。但是如果我在返回字符串的上传方法中调用它,它就搞砸了!
<script type="text/javascript">
$(window).load(
function () {
$("#fileuploader").fileUpload({
'uploader': '/Scripts/uploader.swf',
'cancelImg': '/Images/cancel.png',
'buttonText': 'Vælg StykListe CSV Fil',
'script': '@Url.Action("Upload","Solar")',
'folder': '/uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.csv',
'multi': true,
'auto': true
});
}
);
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 forms-authentication