我有一个正在运行的带有 Forms 身份验证的 MVC 3 (Razor) 应用程序。我可以在局部 View 中轻松调用 @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,它会毫无问题地返回用户名。但是如果我在返回 String 的 Upload 方法中调用它,它就会搞砸!
<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
});
}
);
最佳答案
看起来您正在使用一些客户端文件上传组件。如果此组件使用 Flash,则很可能没有随请求发送 cookie。你可以看看 following blog post它说明了如何将身份验证 cookie 值作为参数发送,并在服务器上重建 token 。这是一个 similar story .
关于c# - MVC 3 表单例份验证 User.Identity.Name 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9105661/