我正在使用ASP.NET Identity,并扩展了IdentityUser类以添加我自己的数据.
我正在使用数据注释来设置某些字段的显示名称等,但由于UserName字段是烘焙的,我无法对其进行注释.由于我打算在该字段中存储电子邮件地址,这是我真正想要重命名的电子邮件地址!
如果数据注释是非启动的(我认为它们是),有没有其他方法可以实现相同的结果?
asp.net-mvc asp.net-mvc-5 asp.net-identity asp.net-identity-2
我在这里描述的问题没有答案,仅使用Unity.
我正在尝试注册ISecureDataFormat<>最新的VS2013(更新2)SPA/Web Api模板.
我试过了
container.RegisterType(typeof(ISecureDataFormat<>), typeof(SecureDataFormat<>));
container.RegisterType<ISecureDataFormat<AuthenticationTicket>, SecureDataFormat<AuthenticationTicket>>();
container.RegisterType<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>();
Run Code Online (Sandbox Code Playgroud)
它"有效"但不是真的,因为它抱怨了该树中的下一个依赖性,IDataSerializer ......然后是下一个IDataProtector,我发现没有实现.
我有一个使用实体框架6的Web应用程序.Identity 2. MVC 4.我将尝试解释我正在处理的事情导致此错误:
异常详细信息:System.Data.SqlClient.SqlException:无效的列名称'UserId'.列名称"UserId"无效.列名称"RoleId"无效.
源错误://在Account Controller.cs中
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
Run Code Online (Sandbox Code Playgroud)
首先,我在实体设计器中添加了AspNetUser表和自定义表"CustomerTicketInfo"之间的关系.我从模型更新了Db并运行了这个自动生成的Sql:
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
-- --------------------------------------------------
-- Date Created: 08/13/2014 10:15:49
-- Generated from EDMX file: C:\Projects\DevTeam\Logistics Mobile MVC\LMSMobile\LMSMobile\Models\LogisticsManagementModel.edmx
-- --------------------------------------------------
SET QUOTED_IDENTIFIER OFF;
GO
USE [LTGLogisticsManagement];
GO
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
GO
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints …Run Code Online (Sandbox Code Playgroud) Visual Studio 2013,Asp.net Identity 2.1.0
我的登录页面(默认情况下由vs2013生成),
(1)有时我可以登录
(2)有时我无法登录.如果登录失败,他们会停留在登录页面上,但在网址末尾会显示"?ReturnUrl = ...".当时打开两个浏览器,一个是IE,另一个是Chrome,然后我发现Chrome成功,IE失败了.
当我成功登录时,我通过使用Fiddler在响应头上看到了这个:
Set-Cookie: .AspNet.ApplicationCookie=MlpChRy8gmGaxxIAo9EFbGrWf4J3mm...._BqMFEFHGuu8fiCNrVvy3LzygcNxlM7snKm9-F-zYrskb4; path=/; HttpOnly
Set-Cookie: .AspNet.ExternalCookie=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: .AspNet.TwoFactorCookie=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
Run Code Online (Sandbox Code Playgroud)
但是当我无法登录时,我看不到这些.
(3)然后其他时间,我得到这个例外:
system.Web.HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Run Code Online (Sandbox Code Playgroud)
但我已经尝试过放入web.config; 我们的系统管理员也向我保证,我们在Web场的服务器上使用相同的机器密钥.
我从来没有在我的本地盒子上遇到任何上述问题,它只发生在我们的测试和测试版服务器上.它在beta服务器上经常发生; 从来没有发生在测试服务器上,但现在它一直在发生.另一位开发人员有时会在他的盒子上遇到问题(2).
这里有什么问题?我好几天都感到沮丧.我觉得这是IIS问题 - 因为它永远不会发生在我的机器上(另一个开发人员可以在他的盒子上有不同的IIS与我的相比).
我正在尝试实现Asp.Net Identity 2.0.到目前为止,我已经在这个博客的帮助下做得很好.但是我的道路略有不同.我希望一些数据不是User对象的一部分,而是一个新创建的Customer对象.我希望将身份验证和授权数据与我的业务数据分开.
所以在我的例子中,我通过添加一个客户属性修改了ApplicationUser类:
public Customer Customer { get; set; }
Run Code Online (Sandbox Code Playgroud)
Customer类看起来像这样:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Insertion { get; set; }
public Gender Gender { get; set; }
public DateTime Birthdate { get; set; }
...etc.
public virtual ApplicationUser User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我还在ApplicationDbContext中添加了关系:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasRequired(u => …Run Code Online (Sandbox Code Playgroud) 我想使用ASP.NET Identity 2和Entity Framework一起使用MySQL进行存储,但我无法让它工作.
我试图按照http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/中的步骤操作,但在运行"启用迁移"时,会出现以下错误:
在类型'Microsoft.AspNet.Identity.EntityFramework.IdentityUser`4 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[Microsoft]上为属性'UserName'指定了冲突的配置设置. AspNet.Identity.EntityFramework.IdentityUserLogin,Microsoft.AspNet.Identity.EntityFramework,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35],[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole,Microsoft.AspNet.Identity.EntityFramework, Version = 2.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35],[Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim,Microsoft.AspNet.Identity.EntityFramework,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35]]' :MaxLength = 256与MaxLength = 128冲突
这就是我所做的:我创建了一个只有类库项目的新解决方案.对于该项目,我已经为Entity Framework和MySQL添加了Nuget包(如上文所述),并通过添加连接字符串修改了app.config:
<add name="MyConnection" connectionString="Datasource=localhost;Database=test1;uid=user;pwd=password;Convert Zero Datetime=True;Allow User Variables=True;" providerName="MySql.Data.MySqlClient" />
Run Code Online (Sandbox Code Playgroud)
项目中唯一的代码是ApplicationContext和ApplicationUser这两个类:
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using MySql.Data.Entity;
namespace Models
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class ApplicationContext : IdentityDbContext<ApplicationUser>
{
/// <summary>
/// To use this constructor you have to have a …Run Code Online (Sandbox Code Playgroud) c# mysql entity-framework visual-studio-2013 asp.net-identity-2
@Roles.GetRolesForUser()在剃刀布局视图中不返回角色.@Roles.GetRolesForUser().Count()是0.
同时在同一视图中@Roles.IsUserInRole('name_of_logged_in_role')返回true同一位置.
剃刀查看:
<p>
@User.Identity.Name //Output: MyName
@Roles.GetRolesForUser().Count() //Output: 0
@Roles.IsUserInRole("Radiologist") //Output: True
</p>
Run Code Online (Sandbox Code Playgroud)
更新
@Roles.GetRolesForUser(User.Identity.Name).Length //Output: 0
@Roles.GetRolesForUser(User.Identity.GetUserName()).Length //Output: 0
Run Code Online (Sandbox Code Playgroud) 我正在使用ASP.NET MVC 5和Identity 2与Entity Framework 6的系统.当用户登录时,我向该登录会话添加一些声明.我不想使用索赔表.
对于我的一个主张,我确实喜欢这样:
public class User : IdentityUser<int, UserLogin, UserRole, UserClaim>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, int> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
//We add the display name so that the _LoginPartial can pick it up;
userIdentity.AddClaim(new Claim("DisplayName", FirstName + " " + LastName));
// Add custom user claims here
return userIdentity;
}
public virtual ICollection<UserInsurance> UserInsurances { get; set; }
public User() …Run Code Online (Sandbox Code Playgroud) asp.net-mvc login claims asp.net-identity asp.net-identity-2
这是我在身份中注册的代码:
[AllowAnonymous]
public ActionResult Register()
{
var roles = db.Roles.Select(r => new { RoleID = r.Id, RoleName = r.Name }).ToList();
ViewBag.Roles = new SelectList(roles, "RoleID", "RoleName");
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase UserPhoto)
{
if (ModelState.IsValid)
{
model.DateRegister = DateTime.Now;
var user = new ApplicationUser
{
UserName = model.UserName,
Name = model.Name,
Family = model.Family,
PhoneNumber = model.PhoneNumber,
Gender = model.Gender,
BirthDay = model.BirthDay,
DateRegister = model.DateRegister,
IsActive = false, …Run Code Online (Sandbox Code Playgroud) 我不喜欢Identity的一件事是,必须在希望获取用户信息的控制器中实例化UserManager。在我的项目中,我将所有业务逻辑都移到了DAL类库中,并希望身份也可以存在。
我已经将所有身份类移到DAL类库中(ApplicationRole,ApplicationUser,ApplicationRoleManager,ApplicationSignInManager,ApplicationUserManager,EmailSerivce,SmsService)
我的DataContext继承自IdentityDBContext
public class DataContext : IdentityDbContext<ApplicationUser>
{
public DataContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
public static DataContext Create()
{
return new DataContext();
}
static DataContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, DataContextMigrationsConfiguration>());
}
Run Code Online (Sandbox Code Playgroud)
因此,我可以通过数据库上下文访问用户和角色
internal class UserRepository
{
internal ApplicationUser GetUserById(string id)
{
using(var db = new DataContext())
{
return db.Users.Where(a => a.Id == id).FirstOrDefault();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我无权访问ApplicationUserManager公开的方法。我正在尝试从用户存储库中访问ApplicationUserManager,但不知道如何实例化ApplciationUserManager类。
在控制器中,其实例化如下
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
} …Run Code Online (Sandbox Code Playgroud)