创建,无法登录用户标识和名称

时间:2018-09-12 06:56:37

标签: c# asp.net asp.net-mvc

我当前正在使用.NET Framework 4.5.1,我不明白为什么“名称”似乎总是不存在。我尝试过

using Microsoft.AspNet.Identity 
User.Identity.GetUserName()

仍然在User上出现以下编译时错误,指出它在当前上下文中不包含?

这是我的创建代码

public void CreateRecord(SampleDataModel Rec)
{

    DefaultConnection ent = new DefaultConnection();

    SampleData dbRec = new SampleData();

    dbRec.CreatedBy = User.Identity.GetUserName(); // <---- CAUSING ERROR

    dbRec.CurrentOwner = Rec.CurrentOwner;
    dbRec.DateOfBirth = Rec.DateOfBirth;
    ent.SampleData.Add(dbRec);
    ent.SaveChanges();
    SampleData DummyObject = new SampleData();

    CreateAuditTrail(AuditActionType.Create, dbRec.ID, DummyObject, dbRec);

}

3 个答案:

答案 0 :(得分:1)

请注意,UserPage类的成员。

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.user

因此,如果您的课程是在尝试获取User成员不是源自Page的成员,则无法通过简单地编写User来访问它。

例如,如果它看起来不是这样:

public partial class _Default : Page

在这种情况下,您将不得不使用更“直接”的方法并使用

HttpContext.Current.User而非仅User

https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcontext.user

因此更改您的行为

dbRec.CreatedBy = User.Identity.GetUserName();

dbRec.CreatedBy = HttpContext.Current.User.Identity.GetUserName();

并添加名称空间

using System.Web;

答案 1 :(得分:0)

原因可能是为应用程序启用了匿名身份验证。允许Windows(如果它在域中)并禁用匿名身份验证。

在Visual Studio中,打开项目属性

enter image description here

在IIS中

enter image description here

答案 2 :(得分:0)

我认为您的问题仅仅是因为您的“用户”未登录。

您确定您具有身份验证方法吗? (通常是一种表格。)

相关问题