【问题标题】:.Net Core API Microsoft.AspNet.Identity.Core.Net Core API Microsoft.AspNet.Identity.Core
【发布时间】:2021-06-16 14:34:45
【问题描述】:

我的问题。

所以我的问题是如何将使用 Microsoft.AspNetCore.Identity 的 .Net Core API 连接到使用 .Net 4.5 和 Microsoft.AspNet.Identity.Core 创建的身份 (AspNetUser) 表

细节。

我有一个 MVC Web 应用程序,它允许用户注册登录,并根据那里的凭据查看某些信息。这是用 .Net4.5 编写的。我假设使用 Microsoft.AspNet.Identity.Core。 (我认为这是非 .NET 核心版本。它不是最好的命名约定)这个项目不能改变。

我正在尝试扩展一些功能,例如登录和注册以使用 API。我正在尝试在 .Net Core 和 Microsoft.AspNetCore.Identity 中构建 API;

我已经创建了一个简单的测试登录控制器。

    [ApiController]
    public class AuthController : ControllerBase
    {

        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly IConfiguration _config;
        public AuthController(UserManager<IdentityUser> userManager,
                              SignInManager<IdentityUser> signInManager,
                                 IConfiguration config)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _config = config; ;
        }

 

      
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginDto user)
        {
            if (ModelState.IsValid)
            {
                var testResult = await _signInManager.PasswordSignInAsync(user.Username, user.Password, false, false);
                return Ok(testResult);
            }
            return BadRequest();
        }
    }

最初我遇到了无效列错误,因为与 .NET4.5 系统创建的 AspNetUsers 表相比,现在创建的 AspNetUsers 表似乎带有额外的字段。

我通过在 dbcontext 类的 ModelBuilder 中忽略它们来解决这个问题

    {

        public AuthConext(DbContextOptions<AuthConext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);


            modelBuilder.Entity<IdentityUser>().Ignore(c => c.PhoneNumberConfirmed)
                                             .Ignore(c => c.TwoFactorEnabled)
                                             .Ignore(c => c.SecurityStamp)
                                             .Ignore(c => c.LockoutEnabled)
                                             .Ignore(c => c.NormalizedEmail)
                                             .Ignore(c => c.NormalizedUserName)
                                             .Ignore(c => c.ConcurrencyStamp)
                                             .Ignore(c => c.LockoutEnd);
        }
    }

但是我没有收到关于 LINQ 查询的错误。

    .Where(i => i.NormalizedUserName == __normalizedUserName_0)' could not be translated. Additional information: Translation of member 'NormalizedUserName' on entity type 'IdentityUser' failed. This commonly occurs when the specified member is unmapped. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& )
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, LambdaExpression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.FindByNameAsync(String normalizedUserName, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByNameAsync(String userName)
   at MyFirstChoice_Api_CORE.Controllers.AuthController.Login(LoginDto user) in C:\Repos\MyFirstChoice_Api_CORE\MyFirstChoice_Api_CORE\Controllers\AuthController.cs:line 43
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

虽然它确实提出了解决方案。我不确定在哪里进行更改,因为我自己并没有创建查询,只是简单地调用 _signInManager.PasswordSignInAsync。

所以我的问题是如何使用 Microsoft.AspNetCore.Identity 连接 .Net Core API 和使用 .net 4.5 和 Microsoft.AspNet.Identity.Core 创建的身份表

【问题讨论】:

    标签: c# asp.net api asp.net-core


    【解决方案1】:

    Microsoft.AspNetCore.Identity 和 Microsoft.AspNet.Identity.Core 似乎没有太多共同点

    What is the difference between Microsoft.AspNet.Identity.Core and Microsoft.AspNetCore.Identity?

    但是 Microsoft.AspNetCore.Identity 是一个 .net 标准库,因此它应该与 .net core / 5 应用程序兼容

    所以你应该尝试在你的 web api 中使用它

    https://www.c-sharpcorner.com/article/authentication-and-authorization-in-asp-net-core-web-api-with-json-web-tokens/

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2019-05-09
      • 2019-04-23
      • 2021-06-25
      • 1970-01-01
      • 2015-10-27
      • 2018-01-29
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多