简体   繁体   English

.Net 核心 API Microsoft.AspNet.Identity.Core

[英].Net Core API Microsoft.AspNet.Identity.Core

My question.我的问题。

So my question is how do I connect a .Net Core API using Microsoft.AspNetCore.Identity to an identity (AspNetUser) table created using .Net 4.5 and Microsoft.AspNet.Identity.Core所以我的问题是如何将使用 Microsoft.AspNetCore.Identity 的 .Net Core API 连接到使用 .Net 4.5 和 Microsoft.AspNet.Identity.Core 创建的身份(AspNetUser)表

The Details.细节。

I have a MVC web application that allows user to register an login, and view certain information based on there credentials.我有一个 MVC Web 应用程序,它允许用户注册登录名,并根据那里的凭据查看某些信息。 This was written in .Net4.5.这是用 .Net4.5 编写的。 and I'm assuming using Microsoft.AspNet.Identity.Core.我假设使用 Microsoft.AspNet.Identity.Core。 (Which I think is the non .NET core version. ITs not the best naming convention) This project cant be changed. (我认为这是非 .NET 核心版本。这不是最好的命名约定)这个项目不能改变。

I'm trying to extend some of the features such as login and register to use an API.我正在尝试扩展一些功能,例如登录和注册以使用 API。 I'm trying to build the API in .Net Core and Microsoft.AspNetCore.Identity;我正在尝试在 .Net Core 和 Microsoft.AspNetCore.Identity 中构建 API;

I have created a simple test login controller.我创建了一个简单的测试登录控制器。

    [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();
        }
    }

Originally I was getting invalid column errors, as it seems that the AspNetUsers table is now created with additional fields compared with the AspNetUsers table created by the .NET4.5 system.最初我遇到了无效列错误,因为与 .NET4.5 系统创建的 AspNetUsers 表相比,现在创建的 AspNetUsers 表似乎带有附加字段。

I got round this issue by ignoring them in the ModelBuilderof the dbcontext class我通过在 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);
        }
    }

However I'm not getting errors regarding the LINQ query.但是,我没有收到有关 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)

While it does suggest a solution.虽然它确实提出了解决方案。 I'm not sure where to make that change as I'm not creating a query myself just simply calling _signInManager.PasswordSignInAsync.我不确定在哪里进行更改,因为我不是自己创建查询,只是简单地调用 _signInManager.PasswordSignInAsync。

So my question is how to I connect and .Net Core API using Microsoft.AspNetCore.Identity to and identity table created using .net 4.5 and Microsoft.AspNet.Identity.Core所以我的问题是如何使用 Microsoft.AspNetCore.Identity 连接 .Net Core API 和使用 .net 4.5 和 Microsoft.AspNet.Identity.Core 创建的标识表

Microsoft.AspNetCore.Identity and Microsoft.AspNet.Identity.Core seem to not have a lot in common Microsoft.AspNetCore.Identity 和 Microsoft.AspNet.Identity.Core 似乎没有很多共同点

What is the difference between Microsoft.AspNet.Identity.Core and Microsoft.AspNetCore.Identity? Microsoft.AspNet.Identity.Core 和 Microsoft.AspNetCore.Identity 有什么区别?

However Microsoft.AspNetCore.Identity is a .net standard library so it should be compatible with .net core / 5 apps然而 Microsoft.AspNetCore.Identity 是一个 .net 标准库,因此它应该与 .net core / 5 应用程序兼容

So you should just try to use it in your web api所以你应该尝试在你的 web api 中使用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM